<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/ DTD/wml_1.1.xml">

<wml>
<head>
<meta http-equiv="cache-control" content="max-age=180,private" />
</head>
<card title="使⽤shell命令⾏添加crontab定时任务">
<p>
作者:<a href="index.php?action=showuser&amp;userid=1&amp;hash=">admin</a><br />时间:2023-05-26 12:24<br />分类:<a href="index.php?action=list&amp;cid=3&amp;hash=">电脑技术</a><br />内容:
使⽤shell命令⾏添加crontab定时任务与使⽤sed来注释恢复crontab中的⼀个任务




⼀、使⽤shell命令⾏ 添加crontab 定时任务


crontab 是运维过程中常⽤的定时任务执⾏⼯具


⼀般情况下在有新的定时任务要执⾏时，使⽤crontab -e ，将打开⼀个vi编辑界⾯，配置好后保存退出，但是在⾃动化运维的过程中往往需要使⽤shell脚本或命令⾃动添加定时任务


⽅法⼀：


编辑 /var/spool/cron/⽤户名 ⽂件，如：




XML/HTML代码


    echo &quot;* * * * * hostname &gt;&gt; /tmp/tmp.txt&quot; &gt;&gt; /var/spool/cron/root 




优点：简单


缺点：需要root权限


⽅法⼆：


编辑 /etc/crontab ⽂件,




XML/HTML代码


    echo &quot;* * * * * root hostname &gt;&gt; /tmp/tmp.txt&quot; &gt;&gt; /etc/crontab




需要注意的是，与常⽤的crontab 有点不同，/etc/crontab 需指定⽤名。⽽且该⽂件定义为系统级定时任务 不建议添加⾮系统类定时任务，编辑该⽂件也需要root权限


⽅法三：


利⽤crontab -l 加 crontab file 两个命令实现⾃动添加




XML/HTML代码


    crontab -l &gt; conf &amp;&amp; echo &quot;* * * * * hostname &gt;&gt; /tmp/tmp.txt&quot; &gt;&gt; conf &amp;&amp; crontab conf &amp;&amp; rm -f conf




由于crontab file会覆盖原有定时任务，所以使⽤ crontab -l 先导出原有任务到临时⽂件 &ldquo;conf&rdquo; 再追加新定时任务


优点：不限⽤户，任何有crontab权限的⽤户都能执⾏


缺点：稍微复杂


⼆、使⽤sed来注释/恢复crontab中的⼀个任务


1. 快速注释包含特定字符串 Log_exception_restart 的⾏




XML/HTML代码


    sed -e &quot;/Log_exception_restart/ s/^/#/&quot; -i /var/spool/cron/root




2. 快速打开特定字符串 Log_exception_restart 的⾏




XML/HTML代码


    sed -e &quot;/Log_exception_restart/ s/^#//&quot; -i /var/spool/cron/root









注意不同系统crontab的目录不太一样，需要注意，根据系统进行修改。




Linux计划任务Crontab 在线生成器


https://crontab.guru/


例子：


https://crontab.guru/#0_8_*_*_5


表示：&ldquo;At 08:00 on Friday.&rdquo;（每周五早上8点） 


</p><p>
<a href="index.php?action=login&amp;hash=">立即登陆发表评论</a><br />
</p>
<p><a href="index.php?action=list&amp;hash=">返回日志列表</a><br /><a href="index.php?action=index&amp;hash=">返回主页</a></p>
</card>
</wml>
