如何定期运行python后台进程 [英] How to run a python background process periodically

查看:80
本文介绍了如何定期运行python后台进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当轻便的脚本,我想每5个小时左右在后台定期运行一次。该脚本运行在几个不同的网站上,对其进行扫描以查找新材料,并从中获取.mp3文件,或者根据其内容在youtube上欣赏歌曲。我不确定要通过该程序实现的一些事情:

I have a fairly light script that I want to run periodically in the background every 5 hours or so. The script runs through a few different websites, scans them for new material, and either grabs .mp3 files from them or likes songs on youtube based on their content. There are a few things I want to achieve with this program that I am unsure of how to attain:


  • 该程序每5小时运行一次-我不熟悉系统级计时操作。

  • 使程序在后台高效运行-我希望这些更新在用户不知情的情况下发生。

  • 在启动时激活程序-我知道如何将其设置为用户,但是我不确定如何将这样的配置添加到python文件中甚至可能。请记住,这将是一个简单的.py脚本-我不会将其编译为可执行文件。

该程序主要是考虑到OSX和其他基于Unix的系统而设计的。对实现其中一些目标有何建议?

The program is designed mainly with OSX and other Unix based systems in mind. Any advice on achieving some of these goals?

推荐答案

如果您的脚本不需要经常执行,听起来好像不需要,我会建议您设置一个cron作业。

If your script doesn't need to be constantly in execution, and it sounds like it doesn't, I'd suggest you set up a cron job.

在典型的Linux机器上,您可以通过以下方式编辑 crontab文件

On a typical Linux box, you can edit your crontab file via:

$ crontab -e

这将在标准编辑器中打开crontab并在完成后为您安装crontab文件(即,将其保存)

This will open your crontab in your standard editor and install the crontab file for you after you're done (i.e. you save it)

A典型的crontab命令如下所示:

A typical crontab command looks like:

# m h  dom mon dow   command
 15  0   *   *   *    /bin/bash /home/yourself/bin/dump_my_tables.sh

此行将执行 dump_my_tables。 sh 每天00:15。您的脚本将需要如下所示:

this line will execute dump_my_tables.sh every day at 00:15. Your script will need a like like the following:

0  */5  *  *  *   /usr/bin/python /home/yourself/bin/scrape_the_web.py

nb:


  • 时间是计算机的本地时间(!)

  • 某些 cron 版本不接受 * / 5 语法,您必须手动指定要计划脚本的时间,即 0,5,10,15,20

  • 您可能想要重定向输出,但超出了答案的范围

  • Time is the machine's local time (!)
  • Some cron versions don't accept */5 syntax, you have to manually specify the hours when you want the script to be scheduled, i.e. 0,5,10,15,20
  • You might want to redirect output, but it's out of this answers' scope

这篇关于如何定期运行python后台进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆