Cron Jobs

Usefult summaries for crontabs

#List the current running cron jobs for currently logged in user:
crontab -l
#remove the jobs from crontab 
#It is a good practice to do so before modifying your script
crontab -r
#add cron jobs
crontab /path/to/backup_script.cron

Modify other user's cron job 

You have to make sure that another user's user name was listed in /etc/cron.allow file.
#Add cron job for another user
crontab -u username -e
#list another user's cron job
xrontab -u username -l

Examples


#run command_1 every 5 minutes (do not miss / in */5)
*/5 * * * * /path/to/command_1
#run command_2 every 5 hours (do not miss / in */5)
0 */5 * * * /path/to/command_2
# run command_3 1:30am everyday
30 1 * * * /path_to_command_3
# run command_4 1pm everyday
0 13 * * * /path_to_command_4

Why Crontab Fails running my command?


Short answer is because of different running environment for command wish to be executed by cron. Cron passes a minimal set of environment variables to your jobs. To see the difference, add a dummy job like this:
* * * * * env > /tmp/env.output
Restart crontab and wait for /tmp/env.output to be created, then remove the job again. Now compare the contents of /tmp/env.output with the output of env running in your regular terminal. The big differences is PATH environment variable. To get around that, set your own PATH variable at the top of the script. E.g.
#!/bin/bash
PATH=/opt/someApp/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# rest of scron script follows

No comments:

Post a Comment

Datatable static image not found on the server

When you use ```datatables.min.css``` and ```datatables.min.js``` locally, instead of datatables CDN, you may have encountered that ```sort...