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

时间:2017-11-19 16:56:44

标签: python timer notifications

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

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

我尝试使用time.sleep,但这不起作用。我想这样:

如果程序将被执行,则不应在接下来的60分钟内再次运行。

我需要在这里使用/编码什么?

感谢您的帮助!

感谢您的提示,我的代码现在看起来像这样(你可以查一下吗?):

**代码部分** =我在现有脚本中合并的代码。

    #!/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**

1 个答案:

答案 0 :(得分:0)

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

以下是一个例子:

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()