Timed Task
Recently, I get a timed check in requirement. On Windows we have lots of applications which provide reminder feature or timed tasks. On Linux, we can use Crontab
and at
to achieve the same thing.
Requirements
Installation:1
pacman -S cronie at
Start and enable the daemon, this will make the service survive from the system reboot:1
2systemctl start cronie at
systemctl enable cronie at
Usage
Both crontab
and at
provide a timed task function. Here I will simply introduce them and then give an example.
crontab
First edit a cron file like mycron
to describe a cron job:1
2# start a job at midnight, every day
0 0 * * * /path/to/your/script
Then use crontab mycron
to load the job, you can use crontab -l
to list all the cron jobs. And to verify this job has been started, check the /var/spool/cron
directory, the job configuration file should be copied here by it before the job started.
at
The command usage is:1
at yourscript time # this will start a job
and atq
will list all the jobs, at -c job_no
will show the job information, atrm job_no
will cancel the job.
Example
I want to automatically start a job randomly between 0:00 and 6:00 every day. Then I edit a script named at.sh
1
2
3
4
5#!/bin/bash
script="/path/to/your/script.sh" #insert the path to your script here
min=$(( 6 * 60 ))
rmin=$(( $RANDOM % $min ))
at -f "$script" now+${rmin}min
and then start a crontab
with the configuration like:1
2# start a job at midnight, every day
0 0 * * * /path/to/at.sh