Running a service/script/program via cronjob

Occasionally while developing a system we need to run a service ( you can say something running in while loop in background supporting other unit in a system), a script ( for example, a python script) or a compiled program (for example ./some_executable some switches like -a -r etc.)

There are many ways to achieve very same thing, one way is Systemd. It is an init system and system manager. There is another way of doing very same thing via cron. It is basically a system daemon used to execute desired tasks (in the background) at designated times.

I have tested this in Debian environment (Yes, it will work with Ubuntu) .

To add script or task to cron just type following in terminal

crontab -e
view raw cron_python_script hosted with ❤ by GitHub

Below is a skeleton example we are going to use for execution, add command like these in the end

*/15 * * * * [path/to/script] #every fifteen minutes
view raw cron_python_script hosted with ❤ by GitHub

Each line has five time-and-date fields, followed by a command, followed by a newline character (‘\n’). The fields are separated by spaces. The five time-and-date fields cannot contain spaces. The five time-and-date fields are as follows: minute (0-59), hour (0-23, 0 = midnight), day (1-31), month (1-12), weekday (0-6, 0 = Sunday).



To run a bash script from a cronjob we can use following

 */15 * * * *  sh /path/fifteenMinlauncher.sh >/pathToLogFolder/fifteenMinlauncherCronlog.log 2>&1  
#every fifteen minutes

To run very same script at reboot we can use following command

@reboot sh /path/fifteenMinlauncher.sh >/pathToLogFolder/fifteenMinlauncherCronlog.log 2>&1
view raw cron_python_script hosted with ❤ by GitHub

>/pathToLogFolder/fifteenMinlauncherCronlog.log 2>&1 This at the end help to dump the execution log to some desired path. Also it doesn’t include any corner case of checking the size of log, that may crash your system.

Don’t forget to give permission to file to be accessible via cron

chmod 755 fifteenMinlauncher.sh
view raw cron_python_script hosted with ❤ by GitHub

let’s say we want to run a python script, in that case you can type following with in that bash script

#!/usr/bin/env bash
cd ~/
cd ~/scripts
sudo python targetPythonScript.py
cd ~/
view raw cron_python_script hosted with ❤ by GitHub

You can specify python directly, but i personally prefer to use single script for firing all units in form of bash script. Python way is like this

@reboot python /path/script.py &
view raw cron_python_script hosted with ❤ by GitHub

Hope this post helped you in some way.

References

  1. https://help.ubuntu.com/community/CronHowto