In Ubuntu use Cron and Crontab to Run Schedule Tasks

Open/Close/Restart Cron in Ubuntu

Config file usurally is /etc/init.d/cron

Start:

1
sudo /etc/init.d/cron start

Close:

1
sudo /etc/init.d/cron stop

Restart:

1
2
sudo /etc/init.d/cron restart
sudo service cron restart

Reload config:

1
sudo /etc/init.d/cron reload

Create a cron task

Normally we use “crontab -u username -e” to add new task in the cron config file.

If edit the exists task, the same command.

running command line

example to write “hello world” to /home/tonytan/helloworld.txt every 5 seconds.

1
*/5 * * * * echo "hello world" >> /home/tonytan/helloworld.txt
use shell file
1
*/5 * * * * /home/tonytan/helloworld.sh

Write the following codes into /home/tonytan/helloworld.sh

1
2
3
#!/bin/sh
cd /home/tonytan/
echo "hello world" >> helloworld.txt

Note: after edit the config file everytime must restart cron, unless unuseable.

1
2
3
4
sudo service cron restart
sudo service cron status #look the cron status
crontab -l #look the cron
crontab -e #edit cron

Attached is the normally example in cron config:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
every 5 sec run task:
*/5 * * * * ?

every 1 min run task:
0 */1 * * * ?

everyday 23:00 run task:
0 0 23 * * ?

everyday 1:00 run task:
0 0 1 * * ?

every month first day 1:00 run task:
0 0 1 1 * ?

every month last day 23:00 run task:
0 0 23 L * ?

every Sunday 1:00 run task:
0 0 1 ? * L

in 26min,29min,33min run task:
0 26,29,33 * * * ?

every day 0:00,13:00,18:00,21:00 run task:
0 0 0,13,18,21 * * ?