简体   繁体   中英

How should I start a node.js script automatically

I want to start my script like every 30-60 minutes and don't want that the script is running all the time.

Can I do some sort of cronjob or something else, that is starting the script and closes it after it's done?

I'm using Ubuntu 18.04

Although cron works, a modern, reliable way to do this on Linux platforms is to create a systemd service. By creating a service, systemd will automatically create a process and restart it if it exits or fails. To create a systemd service, do the following.

  1. Create a file in /etc/systemd/system with the .service extension. This file specifies the process we want systemd to keep an eye on.

  2. In the file, we can choose what command starts the script, how long to wait before retrying if the processes exits, what user is creating the process, etc. This article and this article both list some common parameters. In your case, you want your file to look something like...

    [Unit]
    Description=Runs script every 30 minutes
    After=network-online.target
    Requires=network-online.target # if your script connects to the internet, for example
    Documentation= # maybe your github or something

    [Service]
    Type=simple
    Restart=always
    RestartSec=1800 # 30 minutes
    User= # Your user, if you need particular permissions for example
    WorkingDirectory= # The working directory you need
    ExecStart= # The command to start the script you need
  1. Start your service with systemctl enable your_service_name.service . This will make sure your service runs each time the system is booted (replace enable with disable to stop the service from starting on boot). If you need it to run during THIS boot, use systemctl start your_service_name.service (switching start with stop does what you expect). This is elaborated on in the articles above.

Create a script file like run_script.sh and put the following code in.

exec node /path/to/your/javascript.js

Then add this run_script.sh to your cronjob. You can use */30 * * * * to run it every 30 min or 0 * * * * to run it hourly.

If your script does not stop by itself, you can add a process.exit() after a condition to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM