CentOS 7定时执行python脚本
<p>在CentOS下,可以使用crontab进行定时任务的处理。</p><p><strong>一、crontab的安装</strong></p>
<p>默认情况下,CentOS 7中已经安装有crontab,如果没有安装,可以通过yum进行安装。</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">yum install crontabs
</pre>
</div>
<p> </p>
<p><strong>二、crontab的定时语法说明</strong></p>
<p>corntab中,一行代码就是一个定时任务,其语法结构可以通过这个图来理解。</p>
<p><img src="https://img2020.cnblogs.com/blog/1960974/202006/1960974-20200621114209350-1365752787.png"></p>
<p> </p>
<p>字符含义如下:</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">* 代表取值范围内的数字
/ 代表"每"
- 代表从某个数字到某个数字
, 代表离散的取值(取值的列表)
</pre>
</div>
<p> </p>
<p>一些常用的时间写法如下:</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">* * * * * //每分钟执行
* */4 * * * //每4小时执行
0 4 * * * //每天4点执行
0 12 */2 * *//每2天执行一次,在12点0分开始运行
* * * * 0 //每周日执行
* * * * 6,0 //每周六、日执行
5 * * * * //每小时的第5分钟执行
</pre>
</div>
<p> </p>
<p><strong>三、配置定时执行python脚本</strong></p>
<p>由于是需要定时执行python脚本,所以应该使用如下命令:</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">python xxx.py
</pre>
</div>
<p> </p>
<p>但是非常重要的一点是要用绝对路径写到命令,否则定时运行失败。因此我们需要先弄清楚python的具体路径。</p>
<p>参考之前写的一篇python安装的文章https://www.cnblogs.com/yangjisen/p/13171063.html,我们在服务器上有python2和python3两个版本,通过如下命令来查看其安装路径。</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;"># which python//查看系统默认安装的python2的路径
/usr/bin/python
# which python3 //查看自行安装的python3的路径
/usr/bin/python3
</pre>
</div>
<p> </p>
<p>用如下命令查看当前系统中的定时任务列表</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;"># crontab -l
</pre>
</div>
<p> </p>
<p>对crontab进行编辑</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;"># crontab -e
</pre>
</div>
<p> </p>
<p>在其中增加如下的内容(每小时的00分执行一个获取微信accesstoken的py脚本),注意python的版本用到了3</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">00 * * * * /usr/bin/python3 /usr/local/wechatapi/wechat_accesstoken.py
</pre>
</div>
<p> </p>
<p>完成后,可以重启一下crontab的服务即可。</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">service crond restart
</pre>
</div>
<p> </p>
<p>*我们在编写py脚本时也需要注意,其中如果有对文件进行操作,也应该使用绝对路径。</p><br><br>
来源:https://www.cnblogs.com/yangjisen/p/13171918.html
頁:
[1]