简体   繁体   English

在特定时间启动和停止 Python 脚本

[英]Start and stop a Python script at a specific time

I am writing a script which will record the user activity in a certain period of time every day.我正在编写一个脚本,该脚本将记录每天特定时间段内的用户活动。 The periods are taken from a JSON response of an API, like this:句点取自 API 的 JSON 响应,如下所示:

[{"working_day": "mon", "work_start_at": "09:00", "work_end_at": "18:00"},
{"working_day": "tue", "work_start_at": "09:00", "work_end_at": "15:00"}]

Let's assume that I can parse these strings in a datetime() format.假设我可以以 datetime() 格式解析这些字符串。 I want to run my function accordingly to these periods and stop my function after "work_end_at".我想根据这些时间段运行我的函数,并在“work_end_at”之后停止我的函数。 I found numerous example of how to run after certain amount of seconds, how to run every day (Python lib schedule) and examples with bash crontab.我找到了许多示例,说明如何在特定秒数后运行、如何每天运行(Python lib schedule)以及使用 bash crontab 的示例。 But nothing of this works for me, because all I want is to start the script at a specific time and stop at a specific time.但这对我不起作用,因为我想要的只是在特定时间启动脚本并在特定时间停止。 And then, run again when the next "shift" comes.然后,当下一个“班次”到来时再次运行。

def start():
    time_periods = working_periods_table.find_all()
    today = datetime.datetime.now().isoweekday()
    for day in time_periods:
        if day["day"] == today:
            start_time = day["work_start_at"]
            end_time = day["work_end_at"]

    schedule.every().week.at(start_time).do(record_activity(idle_time=300))

If I've understood what you're asking, you could use while loops.如果我明白你在问什么,你可以使用 while 循环。 Have it periodically check the current time with the times for the shift beginning and end.让它定期检查当前时间和班次开始和结束的时间。 Below is a guide of what I mean, but I'm not sure the comparisons will work.以下是我的意思的指南,但我不确定这些比较是否有效。

from time import sleep

def start():
    time_periods = working_periods_table.find_all()
    today = datetime.datetime.now().isoweekday()
    for day in time_periods:
        if day["day"] == today:
            start_time = day["work_start_at"]
            end_time = day["work_end_at"]

    while True:
        if datetime.datetime.now() >= start_time:
            while True:
                schedule.every().week.at(start_time).do(record_activity(idle_time=300))
                if datetime.datetime.now() >= end_time:
                    break
            break
        else:
            sleep(100)

I have some way to start my process at certain time but can not stop at certain time, I think you might means after running at 1 hour, even it is not finished yet, still stop the program.我有一些方法可以在某个时间启动我的进程,但不能在某个时间停止,我想你可能意味着在运行 1 小时后,即使还没有完成,仍然停止程序。 in this case you might can use while loop在这种情况下,您可以使用 while 循环

take a look with my scripts first this might helpful首先看看我的脚本这可能会有所帮助

import time
from time import strftime, localtime
import datetime

now = datetime.datetime.now()
year = int(now.strftime("%Y"))
month = int(now.strftime("%m"))
day = int(now.strftime("%d"))
hour = int(now.strftime("%H"))

start_time_t = datetime.datetime(year=year, month=month, day=day, hour=22, minute=0, second=0)
waiting_time = time.mktime(start_time_t.timetuple()) - time.time()
if waiting_time >= 0:
    print('the program will be start after ' + time.strftime("%H hours and %M minutes", time.gmtime(waiting_time)))
    time.sleep(waiting_time)
else:
    start_time_t = datetime.datetime(year=year, month=month, day=day + 1, hour=00, minute=0, second=0)
    waiting_time = time.mktime(start_time_t.timetuple()) - time.time()
    print('the program will be start after ' + time.strftime("%H hours and %M minutes", time.gmtime(waiting_time)))
    time.sleep(waiting_time)

It will runs my program every day at 10:00 PM, if pass 10:00 PM the program will runs on the beginning of text day.它将在每天晚上 10:00 运行我的程序,如果超过晚上 10:00,程序将在文本日的开始运行。

If you want to run your script at specific time intervals , I will suggest the code below which I have used on my own script.如果你想在特定的时间间隔运行你的脚本,我会推荐下面我在我自己的脚本中使用的代码。 So simple to implement.实现起来如此简单。

import datetime
now = datetime.datetime.now()

print(now.year, now.month, now.day, now.hour, now.minute, now.second)
# 2015 5 6 8 53 40


while True:
    now = datetime.datetime.now()
    if 14 <= now.hour and 23=> now.hour:
        # put your code here 

Note that in this piece of code I consider 2 PM until 11 PM.请注意,在这段代码中,我考虑了下午 2 点到晚上 11 点。 And more important you have to get the current hour persistently in a loop.更重要的是,您必须在循环中持续获取当前小时。

If you have a specific day in your mind get your current day out of the loop and compare it to your get value !!如果您有特定的一天,请将当前日期排除在循环之外,并将其与您的获取值进行比较!! It works for me.它对我有用。

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

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