在Linux环境上创建定时任务时可以使用crontab来实现。
crontab的参数及书写格式如下:
Usage:
crontab [options] file
crontab [options]
crontab -n [hostname]
Options:
-u <user> define user
-e edit user's crontab
-l list user's crontab
-r delete user's crontab
-i prompt before deleting
-n <host> set host in cluster to run users' crontabs
-c get host in cluster to run users' crontabs
-s selinux context
-x <mask> enable debugging
其中最常用的例子有
crontab -l ----------------------------列出当前用户已有的任务列表
crontab -e -----------------------------编辑当前用户的任务列表(最好不要使用这种方式修改,下面会给出一种比好的方式)
crontab -r -----------------------------删除当前用户的任务列表
下面来举一个给当前用户新加一个任务的例子:
待执行的任务脚本:task.sh
#!/bin/bash
curDir=`pwd`
log=$curDir/task.log
main()
{
time=`date +%Y%m%d%H%M%S`
echo "${time} do something" >> $log
}
main #@
添加定时任务的脚本:addTask.sh
#!/bin/bash
curDir=`pwd`
task=$curDir/task.sh
tmp=/tmp/cronTmp
if [ -f $task ]
then
chmod 750 $task
crontab -l | grep -v "$task" > $tmp > /dev/null 2>&1
echo "0-59 23 * * * $task > /dev/null 2>&1" >> $tmp
crontab $tmp
if [ -f $tmp ]
then
rm -f $tmp 2 > /dev/null
fi
fi
简单说一下crontab中的命令格式:
例如:
0-59 23 * * * /home/jeremysong/cron/task.sh > /dev/null 2>&1
上面的这个命令主要分为两部分,第一部分为运行周期的设定,第二部分则为执行的命令
基本语法有如下的定义:
* * * * * command
分 时 日 月 周 命令
第1列表示分钟1~59 每分钟用*或者 */1表示
第2列表示小时1~23(0表示0点)
第3列表示日期1~31
第4列表示月份1~12
第5列标识号星期0~6(0表示星期天)
第6列要运行的命令
上述的例子表示为:每天的23点,每隔1分钟执行一次task.sh
任务没有立即生效的解决办法:
1、首先确认添加任务是否成功,可以使用crontab -l 的方式查看当前的任务列表
2、确认定时任务执行的command是可执行的
3、使用 /etc/init.d/cron reload 重新加载任务列表
4、最后实在不行,可以使用 /etc/init.d/cron restart 重启服务
另外,crontab任务列表对应的文件为:
/var/spool/cron/tabs(注意:有的系统没有tabs这一层目录)
上述目录中存在的文件即为各个用户的crontab列表文件,例如:root、jeremysong
以上就是对crontab作的一些小总结。另外,crontab的使用不仅局限与如此,配合其他参数还可以设定更加和你项目要求的定时任务。