Python调度程序未运行导入中安排的函数

问题描述 投票:1回答:1

问题

当这段代码:

# main.py - this file gets run directly.
import sched
import time
scheduler = sched.scheduler(time.time, time.sleep)

print("before definition")

def do_something():
    print("do_something is being executed.")
    scheduler.enter(1, 5, do_something)

print("post definition")
scheduler.enter(1, 5, do_something)

# Do something, so that the program does not terminate.
do_not_terminate()

在被调用的文件(main.py)中,它按预期运行(每秒运行do_something函数。),产生以下输出:

before definition
post definition
do_something is being executed.
do_something is being executed.
do_something is being executed.
do_something is being executed.
do_something is being executed.
do_something is being executed.
...

But:

当上面的块被放入一个单独的文件(someimport.py)并且someimport.py被导入main.py时,do_something函数不再被执行。 [代码如下所示:]

# someimport.py - this file gets imported in main.py
import sched
import time
scheduler = sched.scheduler(time.time, time.sleep)

print("before definition")

def do_something():
    print("do_something is being executed.")
    scheduler.enter(1, 5, do_something)

print("post definition")
scheduler.enter(1, 5, do_something)

# main.py - this file get's run directly
import someimport

# Do something, so that the program does not terminate.
do_not_terminate()

仅生成以下输出(当然不会显示错误消息):

before definition
post definition

I already tried the following:

1. Switch import someimport to from someimport import * in main.py

正如预期的那样,这并没有改变任何东西。

2. Put the first scheduler.enter call into a separate function(run), which is called after the import:
# someimport.py - this file gets imported in main.py
import sched
import time
scheduler = sched.scheduler(time.time, time.sleep)

print("before definition")

def do_something():
    print("do_something is being executed.")
    scheduler.enter(1, 5, do_something)

print("post definition")
def run():
    scheduler.enter(1, 5, do_something)

# main.py - this file get's run directly
import someimport

someimport.run()

# Do something, so that the program does not terminate.
do_not_terminate()

这并没有改变任何事情。

3. importing sched and time in main.py aswell.

正如所料,这也没有任何影响。

有没有办法在someimport.py中安排do_something函数,而没有main.py文件中的第一个scheduler.enter。这是我试图避免的事情(因为在真正的项目中有大约100个这样的计划任务,我正在尝试清理主文件)。

上面的所有代码都在GNU / Linux下的python 3.7.3上进行了测试。

提前谢谢了!

python python-3.x import scheduler
1个回答
0
投票

我只能通过在run()实例上将scheduler导入main.py后才能使你的单独模块示例工作。

# main.py - this file get's run directly
import someimport

someimport.scheduler.run()  # Blocks until all events finished

生产:

before definition
post definition
do_something is being executed.
do_something is being executed.

根据the docs,必须调用scheduler.run()才能执行任何计划任务。它本身的scheduler.enter()方法只是安排事件,而不是运行它们。

© www.soinside.com 2019 - 2024. All rights reserved.