2

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

1
  • 1
    Yes, you can setup a cron job to start a script. Does the script close itself when finished or do you want to kill it? You could kill it with the cronjob as well. Commented Feb 6, 2020 at 17:48

2 Answers 2

4

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.
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.