Linux – run a scheduled job once
Posted by danielMar 1
Linux – run a scheduled command once
When we think of running scheduled tasks in Linux, the first tool which comes to mind to most Linux users and admins is cron. Cron is very popular and useful when you want to run a task regularly – say after a given interval, hourly, weekly or even every time the system reboots. The scheduled tasks are faithfully executed by the crond daemon based on the scheduling we set, if somehow crond missed the task because the machine was not running 24/7, then anacron takes care of it. My topic today though is about at which executes a scheduled task only ones at a later time.
1. Adding future commands interactively –
Let us schedule to run a specific command 10 minutes from now, press CTRL+D once you have entered the command –
daniel@lindell:~$ at now +10 minutes at> ps aux &> /tmp/at.log [[PRESS CTRL+D HERE]] job 4 at Wed Mar 1 21:24:00 2017
Now the above command ‘ps aux’ is scheduled to run 10 minutes from now, only once. We can check the pending jobs using atq command –
daniel@lindell:~$ atq 4 Wed Mar 1 21:24:00 2017 a daniel
2. Remove scheduled jobs from queue using atrm or at -r –
daniel@lindell:~$ at now +1 minutes at> ps aux > /tmp/atps.logs at> <EOT> job 8 at Wed Mar 1 21:25:00 2017 daniel@lindell:~$ atq 8 Wed Mar 1 21:25:00 2017 a daniel daniel@lindell:~$ atrm 8 daniel@lindell:~$ atq daniel@lindell:~$
3. Run jobs from a script or file.
In some cases the job you want to run is a script –
daniel@lindell:~$ at -f /tmp/myscript.sh 8:00 AM tomorrow daniel@lindell:~$ atq 11 Thu Mar 2 08:00:00 2017 a daniel
4. Embed shell commands inline –
at now +10 minutes <<-EOF if [ -d ~/pythonscripts ]; then find ~/pythonscripts/ -type f -iname '*.pyc' -delete fi EOF
5. View contents of scheduled task using ‘at -c JOBNUMBER’ :
daniel@lindell:~$ at now +10 minutes <<-EOF > if [ -d ~/pythonscripts ]; then > find ~/pythonscripts/ -type f -iname '*.pyc' -delete > fi > EOF job 13 at Wed Mar 1 21:51:00 2017 daniel@lindell:~$ atq 11 Thu Mar 2 08:00:00 2017 a daniel 12 Wed Mar 1 21:45:00 2017 a daniel 13 Wed Mar 1 21:51:00 2017 a daniel daniel@lindell:~$ at -c 13 [[ TRUNCATED ENVIRONMENTAL STUFF ]] cd /home/daniel || { echo 'Execution directory inaccessible' >&2 exit 1 } if [ -d ~/pythonscripts ]; then find ~/pythonscripts/ -type f -iname '*.pyc' -delete fi
In this small tutorial about at utility, we saw some of the use cases for at – especially where we had to execute a scheduled task only once. The time specification it uses is human friendly, example it supports time specs such as midnight, noon, teatime or today. Feel free to read the man pages for details.
References –
No comments
You must be logged in to post a comment.