crontab
所以首先创建这样一个目录吧!
mkdir -p /var/spool/cron/crontabs
然后编辑要执行的任务
crontabs -e
crontab 是用来让使用者在固定时间或固定间隔执行程序之用,换句话说,也就是类似使用者的时程表。
按照网上查找的资料执行时经常会碰到这种错误:
crontab: chdir(/var/spool/cron/crontabs): No such file or directory
所以首先创建这样一个目录吧!
mkdir -p /var/spool/cron/crontabs
然后编辑要执行的任务
crontabs -e
0 /1 * * /sbin/ntpdate 192.168.1.67 >/dev/null 2>&1 每隔一个小时更新下时间,不打印任何信息
最后,执行下
crond
此时你会发现/var/spool/cron/crontabs下有一个跟用户名相同的文件,保存着要执行的任务。
ps下会发现cron进程已经启动!
# * * * * * user-name command to be executed
crontab -l
crond
当crontab失效时,可以尝试以下语句,以便解决问题
root@kali:~# /etc/init.d/cron restart
root@kali:~# service cron restart
crond: invalid option -- h
BusyBox v1.26.2 (2018-01-10 11:31:43 CST) multi-call binary.
Usage: crond -fbS -l N -L LOGFILE -c DIR
-f Foreground
-b Background (default)
-S Log to syslog (default)
-l N Set log level. Most verbose:0, default:8
-L FILE Log to FILE
-c DIR Cron dir. Default:/var/spool/cron/crontabs
内容为:
*/1 * * * * echo '123' >> /root/123.txt
*/1 * * * * echo '666' >> /root/123.txt
命令行:
mkdir -p /var/spool/cron/crontabs
crontab /etc/crontab
crond
vi /etc/crontab
*/1 * * * * echo '123' >> /root/123.txt
*/1 * * * * echo '666' >> /root/123.txt
下一步是 键入启动脚本中去
/etc/init.d/rcS
mkdir -p /var/spool/cron/crontabs
crontab /etc/crontab
crond
python 脚本执行:
绝对路径问题
crontab中python命令使用绝对路径,如:
Python代码 收藏代码
/5 * * * /usr/local/bin/python2.7 /home/work/user/main.py > /yyy.log 2>&1
程序中涉及文件路径,相对路径改为绝对路径,如:
Python代码
file = 'conf'
改为:
file = '/home/work/user/conf'
测试脚本:append_file.py
# -*- coding:utf-8 -*-
from append_func import func
def main():
print 'append_file'
func()
if __name__ == "__main__":
main()
测试脚本:append_func.py
# -*- coding:utf-8 -*-
def func():
with open('/root/555.txt', 'a+') as f:
f.write('567\r\n')
/etc/crontab 内容为:
*/1 * * * * echo '123' >> /root/123.txt
*/1 * * * * echo '666' >> /root/123.txt
*/1 * * * * /usr/bin/python /root/append_file.py