使用Python进行Cron自动化测试

-5 投票
2 回答
889 浏览
提问于 2025-04-17 07:03

我该怎么每10秒运行一次我的“Hello world”脚本呢?

我知道这个问题有点傻,因为谷歌上有很多答案。

谢谢你的帮助。

2 个回答

1

有很多方法可以实现你想要的效果。我能想到的最简单的方法是:

>>> from time import sleep
>>> while True:
...     sleep(10)
...     print 'hello!'

编辑:如果你的脚本还需要做其他事情,这里有一个稍微修改过的版本(请查看评论):

>>> from time import time
>>> counter = time()
>>> while True:
...     if time() - counter > 10:
...         counter = time()
...         print 'hello!'
...     pass  #do other stuff here
2

如果你想每10秒执行一次任务,单靠系统的定时任务(cron job)是不够的,因为它的精确度只能到分钟。

不过,你可以使用高级Python调度器(Advanced Python Scheduler)来实现这个功能。

from apscheduler.scheduler import Scheduler

# Start the scheduler
sched = Scheduler()
sched.start()

def job_function():
    print "Hello World"

# Schedules job_function to be run every 10 seconds
sched.add_cron_job(job_function, second='*/10')

撰写回答