Reputation: 105
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
Upvotes: 2
Views: 1274
Reputation: 79
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.
Create a file in /etc/systemd/system
with the .service
extension. This file specifies the process we want systemd to keep an eye on.
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
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.Upvotes: 4
Reputation: 345
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.
Upvotes: 2