美文网首页
Crontab使用

Crontab使用

作者: AnyL8023 | 来源:发表于2016-12-06 17:31 被阅读0次

在Linux终端输入:

crontab -h

可以看到:

usage:  crontab [-u user] file
    crontab [ -u user ] [ -i ] { -e | -l | -r }
        (default operation is replace, per 1003.2)
    -e  (edit user's crontab)
    -l  (list user's crontab)
    -r  (delete user's crontab)
    -i  (prompt before deleting user's crontab)

这里可以通过

crontab -e

对于定时任务进行编辑。
这样就进入到了编辑页面:

# 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

看到最后一行:

分 小时 日 月 星期 命令

输入:

0 * * * * /home/ubuntu/run.sh

表示每小时会执行run.sh
“*”代表取值范围内的数字,
“/”代表”每”,
“-”代表从某个数字到某个数字,
“,”分开几个离散的数字

重启cron服务:

service cron restart

通过相关指令查看进程:

ps -ax | grep cron 

在ubuntu下安装crontab后,系统默认的是不开启crontab的日志记录的,启用crontab的日志的办法:
1.修改rsyslog文件,将/etc/rsyslog.d/50-default.conf 文件中的#cron.*前的#删掉;
重启rsyslog服务service rsyslog restart;
重启cron服务service cron restart;
2.more /var/log/cron.log就可以查看运行时的日志文件,如果在日志文件中出现:No MTA installed, discarding output
那么就是说,crontab执行脚本时是不会直接错误的信息输出,而是会以邮件的形式发送到邮箱里,这时候就需要邮件服务器了,如果没有安装邮件服务器,就会报这个错。如果是测试,可以用下面的办法来解决:
在每条定时脚本后面加入:>/dev/null 2>&1。就可以解决No MTA installed, discarding output的问题。

相关文章

网友评论

      本文标题:Crontab使用

      本文链接:https://www.haomeiwen.com/subject/blprmttx.html