Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

For a Node.js task that should run independently every minute, hour, or day, use the Linux user crontab with an absolute Node binary path, an absolute script path, an explicit working directory, and captured logs. Use node-cron when the schedule belongs inside an application that is already running, and use PM2 when that application also needs restart, reboot persistence, and process supervision.

The most common reason a job works in SSH but fails in cron is that cron starts a different, minimal shell environment. Treat the schedule as a production service: choose its timezone, define its environment, prevent harmful overlap, log both output streams, and verify the exact command as the same user that owns the crontab.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the scheduler before writing the schedule

The three approaches solve different operational problems. Choosing by the job’s lifecycle avoids many reliability problems later.

Scheduler Use it when What it does Important limitation
Linux system cron A command should start at a time and finish, regardless of whether a Node process is already running. The cron daemon reads the owner’s crontab and launches the command through the configured shell. It does not supervise a continuously running Node application or automatically provide application-level locking.
node-cron The schedule is part of a continuously running Node.js application and needs application state, services, or shared code. The npm library evaluates cron expressions inside the Node process and invokes a callback when they match. The process must remain alive; if it exits, the schedule stops. Expression extensions, including an optional seconds field, depend on the installed package version.
PM2 The application must stay alive, restart after crashes, start after reboot, and expose operational controls. PM2 supervises the process, can restore a saved process list at boot, and supports scheduled restarts with cron_restart. A restart schedule is not the same as a one-shot job. In cluster mode, every worker can execute in-process schedule code unless you deliberately make it singleton.

A practical rule is simple: put independent backups, reports, cleanup commands, and imports in system cron; put stateful recurring logic in node-cron; use PM2 around an application that must stay available and recover automatically. You can combine them, but assign one clear owner to each schedule so two mechanisms do not trigger the same work.

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application: attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Economical &Reusable: Built durable materials with a long-lasting battery,our CAGIWIRU air duster it's a sustainable alternative to disposable air cans.

Understand Linux cron’s timing model

A standard user crontab entry contains five time fields followed by a command:

minute hour day-of-month month day-of-week command

Linux cron examines entries every minute. The fields accept single values, comma-separated lists, ranges, and step values. The following examples use the crontab’s local time:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Expression Meaning
* * * * * Every minute
0 * * * * At minute zero of every hour
*/15 * * * * Every 15 minutes
0 3 * * * Every day at 03:00
30 2 * * 1-5 At 02:30 on Monday through Friday
0 0 1 * * At midnight on the first day of every month

When both day-of-month and day-of-week are restricted, cron runs when either restricted field matches. This differs from an “and” interpretation and is a frequent source of unexpected extra runs.

Timezone and daylight-saving transitions

Decide which timezone the job represents before choosing an expression. Cron uses the daemon and host timezone unless you configure your platform otherwise. During a daylight-saving transition, a local time can be nonexistent and be skipped, or a repeated wall-clock time can occur twice. A job scheduled for 02:30 can therefore miss a spring transition or run twice during a fall transition. For billing, notifications, and other sensitive work, document the intended timezone and make the operation safe if a timestamp is delivered twice.

Prepare a reliable Node.js entry point

Create a small script whose only responsibility is one invocation of the job. Keep business logic in modules so the same function can be called from a manual command, cron, a test, or an application scheduler.

// /srv/myapp/jobs/backup.js
'use strict';

async function main() {
  // Perform one complete backup and resolve only when it is finished.
  console.log(`backup started at ${new Date().toISOString()}`);
  // await runBackup();
  console.log('backup completed');
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

The promise must settle only after the work is complete. If the script starts asynchronous work and exits first, cron records a successful process while the actual operation is still running or has been abandoned. Return a non-zero exit status for failures so logs, monitoring, and mail can distinguish success from an error.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Make repeated execution safe

Assume that a process can be retried, delayed, or started twice. An idempotent job produces the same final state when the same input is processed again. Examples include using a stable record key for database writes, writing a temporary file and renaming it atomically, and recording a run identifier before sending an external notification.

If duplicate execution would be harmful, add an application lock or a lockfile strategy. A lock needs an owner, an expiry or stale-lock recovery plan, and cleanup when the process exits. A lock that can remain forever after a machine crash is worse than no lock unless you can safely detect and clear stale ownership. For long-running jobs, also decide whether a second invocation should wait, exit immediately, or be skipped.

Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth

Use paths and permissions the job can actually reach

  • Store the script in a stable absolute location such as /srv/myapp/jobs/backup.js, not a path relative to the directory from which you happened to test it.
  • Ensure the crontab owner can read the script and every parent directory, and can write any output, temporary, or data directory the job uses.
  • Do not assume the interactive SSH account is the same account that owns the scheduled task. A per-user crontab runs with that user’s identity.
  • Keep secrets out of the crontab line where possible. Use a protected environment file or a secret store, and restrict its permissions so other users cannot read it.

Install a one-shot job in a user crontab

The crontab command manages per-user tables. Do not edit the cron spool files directly; use the command-line editor and verify the resulting table.

  1. Find the Node binary used by the account that will own the job:

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
    command -v node

    Record the absolute result, such as /usr/bin/node. If the command prints an NVM-managed path, use that exact binary in cron or deliberately load a controlled environment file.

  2. Confirm the script manually with its production working directory and the same user:

    cd /srv/myapp && /usr/bin/node /srv/myapp/jobs/backup.js
  3. Create a log location writable by that user. A user-owned directory avoids permission failures:

    mkdir -p /srv/myapp/logs
  4. Open the user’s crontab:

    crontab -e
  5. Add explicit shell and path settings, then the schedule. Adapt every path, username, and timezone decision to your VPS:

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
    SHELL=/bin/sh
    PATH=/usr/local/bin:/usr/bin:/bin
    MAILTO=
    0 3 * * * cd /srv/myapp && /usr/bin/node /srv/myapp/jobs/backup.js >> /srv/myapp/logs/backup.log 2>&1

    The expression starts the command at 03:00 each day in the crontab’s local time. The cd establishes the working directory, >> appends standard output, and 2>&1 sends standard error to the same log.

  6. Save and exit the editor, then inspect the installed table:

    Rank #3
    Sale
    BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black | LED mouse pad with 14 lighting modes, covers keyboard & mouse, anti-slip rubber base, waterproof surface, USB powered
    • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
    • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
    • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
    • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
    • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.
    crontab -l
  7. For an initial test, temporarily use * * * * *, wait for one or two minutes, inspect the log, and restore the intended expression. Remove the test entry rather than leaving an accidental every-minute task.

A system-wide entry in /etc/crontab or a file under /etc/cron.d has an additional user field, but a standard user crontab does not. Mixing those formats causes the command to be parsed incorrectly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Reproduce the environment cron will receive

An interactive shell often loads profile files, NVM initialization, aliases, a project directory, and application variables. Cron normally starts a minimal shell, so none of those assumptions are safe.

NVM and other version managers

NVM is a shell function and environment setup, not simply a globally available executable. Cron will not automatically reproduce an interactive shell’s NVM initialization. The most deterministic solution is to call the real Node binary returned by command -v node. If you must source an environment file, make it short, controlled, and suitable for non-interactive execution; avoid sourcing a full interactive profile that prints text or depends on a terminal.

Working directory and module resolution

Relative paths, process.cwd(), local configuration files, and package resolution can change when cron starts a command. Prefix the command with cd /srv/myapp &&, or set the working directory through the process manager you use. Prefer absolute paths for files that are not intentionally relative to the project root.

Environment variables

Declare required values explicitly. You can place simple assignments above the cron entry:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
APP_ENV=production
DATABASE_URL=...
0 3 * * * cd /srv/myapp && /usr/bin/node /srv/myapp/jobs/backup.js >> /srv/myapp/logs/backup.log 2>&1

Do not expose passwords in a world-readable crontab or in a command line visible through process inspection. For sensitive values, use a file readable only by the job user or an operating-system secret mechanism, then have the script load it securely.

Shell behavior and command syntax

The crontab’s SHELL controls how the command is interpreted. Bash-only syntax, shell aliases, and interactive functions can fail under /bin/sh. Use portable shell syntax or invoke the required shell explicitly. Quote paths containing spaces, although avoiding spaces in service paths is simpler.

Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.

Logging, exit status, and alerts

Always capture both output streams during setup and keep a retention plan for the resulting log. A growing log can eventually fill the VPS disk and prevent unrelated services from writing.

  • Standard output: normal progress and completion messages.
  • Standard error: stack traces, rejected promises, and operational failures.
  • Exit status: zero should mean the complete operation succeeded; a non-zero status should represent failure.
  • Mail: cron can mail output to the crontab owner or an address in MAILTO when local mail delivery is configured. Setting MAILTO= disables that mail and makes file logging your responsibility.
  • Daemon logs: the cron service may also record job activity through syslog, depending on the Linux distribution and its logging configuration.

After a run, inspect the application log and the host’s cron or syslog records. A missing application log can mean the command never started, the redirection path is not writable, or the script terminated before writing anything; it is not proof that the schedule was never evaluated.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use node-cron for schedules inside a running application

Install the library in the application that will remain alive, then register the schedule during startup:

const cron = require('node-cron');

cron.schedule('0 3 * * *', async () => {
  try {
    await runBackup();
    console.log('scheduled backup completed');
  } catch (error) {
    console.error('scheduled backup failed', error);
  }
});

The expression above uses the usual five fields and runs at 03:00 according to the process’s scheduling context and package behavior. Some versions support an optional seconds field, but that is a library feature rather than a property of standard Linux cron. Check the installed node-cron version’s documentation before using six-field expressions or timezone options.

Keep the process alive under a supervisor; a plain node app.js launched from an SSH session will end when the session or process ends. Also guard against overlap inside the callback. For example, an in-memory running flag can prevent concurrent callbacks within one process, but it does not coordinate multiple processes or cluster workers; use a shared lock for that case.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use PM2 for process supervision and reboot persistence

PM2 is appropriate when the Node application itself must stay alive. A typical first deployment looks like this:

  1. Start the application with a stable name:

    pm2 start /srv/myapp/app.js --name myapp
  2. Ask PM2 to generate the startup integration for the VPS:

    pm2 startup

    PM2 prints a command, often requiring elevated privileges and the correct user environment. Execute the exact command it prints.

    Best Value
    Sale
    Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
    • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
    • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
    • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
    • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
    • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.
  3. Save the currently managed process list:

    pm2 save
  4. Verify status and logs:

    pm2 status
    pm2 logs myapp

When using an ecosystem file, define the working directory and environment there so restarts are reproducible. PM2 also supports a cron_restart setting for restarting a process on a cron pattern. A restart is useful for periodic recycling or a scheduled reload; it is not a substitute for a script that must execute once and then exit.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If Node was installed through NVM and you change the active Node version, refresh the PM2 startup configuration and save the process list again. The startup command embeds the runtime environment; leaving it pointed at an old NVM path can make the application fail only after reboot.

Prevent duplicate schedules in cluster mode

If PM2 runs several workers and each worker registers the same node-cron callback, every worker can execute it. Keep singleton schedules in one dedicated process, gate execution by instance identity, or coordinate through a distributed lock. Verify the behavior against the PM2 version and ecosystem configuration deployed on your VPS rather than assuming one callback means one execution globally.

Make reboot and long-running operation predictable

System cron does not require a Node process to be running before the scheduled minute; the daemon starts the command when the time matches. That makes it a good fit for independent jobs after a reboot, provided the cron service is enabled and the job’s paths, permissions, and environment are available at boot.

A node-cron schedule, by contrast, exists only after its Node process has started. PM2 startup plus pm2 save restores that process after reboot. For either design, test a real reboot or an equivalent service restart during a maintenance window, then check the first expected run and its logs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshoot by comparing the execution context

The command works in SSH but not in cron

  1. Run command -v node as the crontab owner and use that absolute path.
  2. Compare PATH, SHELL, and required variables with the interactive shell.
  3. Add cd to the project directory and replace relative file paths.
  4. Check execute and read permissions on the script and every parent directory.
  5. Run the exact command as the same user, without relying on aliases, profile files, or NVM initialization.
  6. Capture both output streams and inspect the log before changing the schedule expression.

There is no output

Confirm the entry with crontab -l, verify that the log directory is writable, and temporarily schedule a harmless one-minute command that writes a timestamp. Inspect the cron daemon’s system log as well. If local mail is configured, set a valid MAILTO address; otherwise, rely on explicit file logging and external monitoring.

The job runs twice around a clock change

Review the host timezone and the daylight-saving transition that occurred. A repeated local time can legitimately match the same wall-clock expression twice. Make the operation idempotent, record a unique run key, or schedule in a timezone without seasonal clock changes when that matches the business requirement.

The job overlaps itself

Measure the longest normal runtime against its interval. Add an application lock or lockfile with stale-lock handling, or move the schedule to a mechanism that provides overlap control. Do not solve overlap by silently killing the previous process unless partial work is safe to abandon.

A PM2 schedule runs once per worker

Check whether the callback is registered in every cluster worker. Move it to one process, gate it by instance identity, or use a shared lock. Inspect the ecosystem configuration and deployed PM2 version before relying on worker-specific environment variables.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The process stops after reboot

For a cron job, verify that the cron daemon is enabled and that the entry belongs to the intended user. For PM2, run the documented startup setup, execute pm2 save, and refresh the startup command after changing an NVM-managed Node version.

Production checklist

  • Choose system cron, node-cron, or PM2 according to whether the work is one-shot, in-process, or continuously supervised.
  • Write down the intended timezone and account for daylight-saving skips and repeats.
  • Use an absolute Node binary and script path, an explicit PATH, shell, working directory, and application environment.
  • Run as the least-privileged account that can complete the job.
  • Make the operation idempotent or implement a lock with safe stale-lock recovery.
  • Redirect standard output and standard error, rotate or retain logs, and define how failures alert an operator.
  • Check exit codes, inspect logs, and verify the installed table with crontab -l.
  • Test the exact non-interactive command before trusting a production schedule.
  • For PM2, verify startup restoration, save the process list, and test cluster behavior if schedules run in application code.

With those controls in place, the schedule itself is the easy part: cron supplies the five-field trigger, Node performs one well-defined operation, and the surrounding environment makes every invocation observable and repeatable.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.