不要在特定时间(例如1小时)内再次运行python脚本

2024-09-30 22:20:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用这个python脚本: LINK

到目前为止效果很好。 但现在我想对它进行优化,因为有时脚本会在10-20分钟内执行2-3次,因为如果有3个或更多流(例如4个流),它将始终运行。流将启动-->;通知将再次发送,或者如果用户决定取消此流并观看另一部电影-->;脚本将再次运行!)你知道吗

我试过使用time.sleep,但那不起作用。我想要这样的:

如果程序将被执行,它不应该在接下来的60分钟内再次运行。你知道吗

我需要在这里使用什么/代码?你知道吗

谢谢你的帮助!你知道吗

谢谢你的提示,我的代码现在看起来是这样的(你能检查一下吗?)地址:

**code section**=我在现有脚本中合并的代码。你知道吗

    #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Description:  Send a PlexPy notification when the total 
#               number of streams exceeds a threshold.
# Author:       /u/SwiftPanda16
# Requires:     requests
# PlexPy script trigger:    Playback start
# PlexPy script arguments:  {streams}

import requests
import sys
**import os
from datetime import datetime, timedelta**


### EDIT SETTINGS ###

PLEXPY_URL = 'xx.xxx.xx:8181'
PLEXPY_APIKEY = 'xxxxxxxxxxxxxxxxxx'
AGENT_ID = 14  # The PlexPy notifier agent id found here: https://github.com/JonnyWong16/plexpy/blob/master/API.md#notify
NOTIFY_SUBJECT = 'test'  # The notification subject
NOTIFY_BODY = 'Test'
STREAM_THRESHOLD = 3

**### time management ###
one_hour_ago = datetime.now() - timedelta(minutes=60)
filetime = datetime.fromtimestamp(os.path.getctime("timestamp.txt"))
if filetime < one_hour_ago:**

### CODE BELOW ###
    def main():
        try:
            streams = int(sys.argv[1])
        except:
            print("Invalid PlexPy script argument passed.")
            return

        if streams >= STREAM_THRESHOLD:
            print("Number of streams exceeds {threshold}.".format(threshold=STREAM_THRESHOLD))
            print("Sending PlexPy notification to agent ID: {agent_id}.".format(agent_id=AGENT_ID))

            params =   {'apikey': PLEXPY_APIKEY,
                        'cmd': 'notify',
                        'agent_id': AGENT_ID,
                        'subject': NOTIFY_SUBJECT,
                        'body': NOTIFY_BODY}

            r = requests.post(PLEXPY_URL.rstrip('/') + '/api/v2', params=params)
            **os.getcwd()
            open ('timestamp.txt', 'w')**
        else:
            print("Number of streams below {threshold}.".format(threshold=STREAM_THRESHOLD))
            print("No notification sent.")
            return


    if __name__ == "__main__":
        main()



**else:
    pass**

Tags: import脚本idstreamdatetimethresholdnotifynotification
1条回答
网友
1楼 · 发布于 2024-09-30 22:20:11

让脚本将时间戳写入外部文件,并在启动时检查该文件。你知道吗

举个例子:

import time

def script_has_run_recently(seconds):
    filename = 'last-run-time.txt'
    current_time = int(time.time())
    try:
        with open(filename, 'rt') as f:
            last_run = int(f.read().strip())
    except (IOError, ValueError) as e:
        last_run = 0
    if last_run + seconds > current_time:
        return True
    else:
        with open(filename, 'wt') as f:
            f.write(str(current_time))
        return False


def main():
    print('running the main function.')


if __name__ == "__main__":
    seconds = 3600  # one hour in seconds
    if script_has_run_recently(seconds):
        print('you need to wait before you can run this again')
    else:
        main()

相关问题 更多 >