ubuntu下定时任务的执行

时间:2021-10-20 21:33:51

概述

linux系统由 cron (crond) 这个系统服务来控制例行性计划任务。Linux 系统上面原本就有非常多的计划性工作,因此这个系统服务是默认启动的。

另外, 由于使用者自己也可以设置计划任务,所以, Linux 系统也提供了使用者控制计划任务的命令 :crontab 命令。

Linux下的任务调度分为两类,系统任务调度和用户任务调度。

系统任务调度:系统周期性所要执行的工作,比如写缓存数据到硬盘、日志清理等。在/etc目录下有一个crontab文件,这个就是系统任务调度的配置文件。

使用者权限文件:

文件:

/etc/cron.deny 说明:该文件中所列用户不允许使用crontab命令

文件:

/etc/cron.allow 说明:该文件中所列用户允许使用crontab命令

文件:

/var/spool/cron/ 说明:所有用户crontab文件存放的目录,以用户名命名

 

crontab文件的含义:

用户所建立的crontab文件中,每一行都代表一项任务,每行的每个字段代表一项设置,它的格式共分为六个字段,前五段是时间设定段,第六段是要执行的命令段,格式如下:

minute   hour   day   month   week   command

ubuntu下定时任务的执行

在以上各个字段中,还可以使用以下特殊字符:

星号(*):代表所有可能的值,例如month字段如果是星号,则表示在满足其它字段的制约条件后每月都执行该命令操作。

逗号(,):可以用逗号隔开的值指定一个列表范围,例如,“1,2,5,7,8,9”

中杠(-):可以用整数之间的中杠表示一个整数范围,例如“2-6”表示“2,3,4,5,6”

正斜线(/):可以用正斜线指定时间的间隔频率,例如“0-23/2”表示每两小时执行一次。同时正斜线可以和星号一起使用,例如*/10,如果用在minute字段,表示每十分钟执行一次。

 

ubuntu下crontab命令的使用

  1.首先编辑crontab文件。

crontab -e #打开你的用户所属的crontab文件。第一次用这个命令,会让你选择文本编辑器

             以后可以通过命令更改编辑器

select-editor

 原始的crontab文件如下: 

# Edit this file to introduce tasks to be run by cron.
# 
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
# 
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').# 
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
# 
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
# 
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
# 
# For more information see the manual pages of crontab(5) and cron(8)
# 
# m h  dom mon dow   command
* * * * * date >> /opt/time.txt #每一分钟执行一次
                           

保存crontab,重启cron来应用这个计划任务。使用以下命令:

sudo service cron restart

效果图如下:

 ubuntu下定时任务的执行