简体   繁体   English

经过一段时间后运行python函数。 使用线程计时器,它只运行一次然后停止

[英]Running a python function after a certain time passes. Using Threading Timer, however it only runs once and then stops

I am trying to run a specific function in my python file. 我试图在我的python文件中运行一个特定的功能。 However, when I run the method with the timer that calls said function, it executes everything that it's supposed to, but then exits the job after the first time. 但是,当我使用调用所述函数的计时器运行该方法时,它会执行它应该执行的所有操作,但在第一次之后退出该作业。 I need it to continue to run the function after the specified time. 我需要它在指定的时间后继续运行该函数。

This is the function that contains the timer: 这是包含计时器的函数:

def executor(file):
        x = datetime.today()
        y = x.replace(day=x.day, hour=x.hour, minute=x.minute, second=x.second+10, microsecond=0)
        delta_t = y-x
        secs = delta_t.seconds+1
        t = Timer(secs, parse_file, [file])
        t.start()

The function that I am trying to call, is parse_file(file_name) . 我试图调用的函数是parse_file(file_name) I am passing in the file_name when calling the executor function. 我在调用executor函数时传入file_name

You haven't given enough detail of what your actual issue is, what code do you want to run more than once? 您还没有详细说明您的实际问题是什么,您希望多次运行哪些代码? Can you show the code that actually calls this function? 你能展示实际调用这个函数的代码吗?

When you call start, the main thread will continue executing from that spot, while the task you scheduled will call the parse_file method at the specified time, and exit once complete. 当您调用start时,主线程将从该位置继续执行,而您计划的任务将在指定时间调用parse_file方法,并在完成后退出。 It sounds to me like you don't have anything that is keeping your main thread alive (that is, you don't have any more code after you call the executor). 听起来像你没有任何让你的主线程保持活动的东西(也就是说,在你调用执行程序之后你没有任何代码)。

Here is a small example showing how you can use the Timer to execute tasks while the main thread is still working. 这是一个小例子,展示了如何在主线程仍在工作时使用Timer执行任务。 You can keep typing in input, and the print statement will show you all the threads that completed since the last time you typed an input. 您可以继续输入输入,print语句将显示自您上次输入输入以来完成的所有线程。

from threading import Timer
import sys

def scheduled_task(arg):
    print("\ntask complete arg %s!\n"%(arg))

def run_scheduled_task(arg):
    timer = Timer(10, scheduled_task, [arg])
    timer.start()

done = False
while not done:
    user_input = input("Give me some input (exit to stop): ")
    if user_input == 'exit':
        print('Exiting')
        done = True
    else:
        run_scheduled_task(user_input)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM