在创建自动任务之前需要安装的安装包:
cron
使用crontab来对当前用户的定时任务进行编辑
crontab -u //设定某个用户的cron服务,一般root用户在执行这个命令的时候需要此参数
crontab -l //列出当前(某个)用户cron服务的详细内容
crontab -r //删除当前(某个)用户的cron服务
crontab -e //编辑当前(某个)用户的cron服务
这里使用root创建的用户,所以直接在root用户下,执行crontab -e编辑好以后然后退出编辑器即可。
如果不放心还可以执行以下/etc/init.d/cron restart
编辑好以后的脚本如下
# 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 25 22 * * 4 /var/auto_script/db_bak/dbbak.sh /var/auto_script/db_bak/dbname.txt 1 >> /var/auto_script/db_bak/autoworker_log.txt
其中的25代表时间的25分钟
22代表时间的22点
4代表每周星期4
/var/auto_script/db_bak/dbbak.sh /var/auto_script/db_bak/dbname.txt 1 >> /var/auto_script/db_bak/autoworker_log.txt 则是命令行
对于cron自身的配置来说,他的配置放在/etc/crontab,内容如下:
# /etc/crontab: system-wide crontab # Unlike any other crontab you don't have to run the `crontab' # command to install the new version when you edit this file # and files in /etc/cron.d. These files also have username fields, # that none of the other crontabs do. SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # m h dom mon dow user command 51 * * * * root cd / && run-parts --report /etc/cron.hourly 40 1 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily ) 48 5 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly ) 28 2 23 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly ) #
对于cron的配置来说,尽量不要去修改,网上有些文章说,如果要执行周期性任务,可以到/etc/cron.*目录下保存脚本,我这边看到的是,大部分都是系统类任务;最好不要去这样做。混淆了脚本的分类很麻烦