运行Python程序直到特定时间

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

我想在jupyter笔记本中运行我的程序,该程序在特定时间停止(例如18:00)。我通过while循环和增量索引编写程序,但最好用time参数编写它。

我每天运行提到的程序7个小时。它必须不间断运行。

    while(i<500000):
         execute algorithm
         i+=1

但是我想像下面这样运行我的程序:

    while(not 18:00 clock):
         execute algorithm
python time while-loop jupyter-notebook
7个回答
1
投票
import datetime

while datetime.datetime.now().hour < 18:
    do stuff...

要么

if datetime.datetime.now().hour >= 18:
    return

1
投票

导入日期时间

https://docs.python.org/3/library/datetime.html

然后,您可以使用各种函数(time或timedelta)来设置时间。

time Now = datetime.datetime()打印时间现在


1
投票

您可以创建一个以小时和分钟为参数的函数,并在while循环中执行检查:

import datetime

def proc(h, m):
    while True:
        currentHour = datetime.datetime.now().hour
        currentMinute = datetime.datetime.now().minute
        if currentHour == h and currentMinute == m:
            break
        # Do stuff...

# Function call.
proc(18,0)

1
投票

使用:

import datetime
#create the alarm clock.
alarm = datetime.time(15, 8, 24) #Hour, minute and second you want.

同时:

while alarm < datetime.datetime.now().time():
    do something

你也可以设置一个特定的日期,设置如下:

datetime.datetime(2019, 3, 21, 22, 0, 0)  #Year, month, day, hour, minute and second you want.

有关更多信息,请查看datetime的文档。


1
投票

您可以创建一个子进程,它将在特定时间终止父进程和自身:

import multiprocessing as mp
import time
import datetime
import sys
import signal
import os

def process(hr, minute):
    while True:
        d = datetime.datetime.now()
        if d.hour == hr and d.minute == minute:
            os.kill(os.getppid(), signal.SIGTERM)
            sys.exit()
        else:
            time.sleep(25)


p = mp.Process(target=process, args=(18, 0))
p.start()

# your program here ...

0
投票

您可以将其设置为cron作业并在时间x开始作业并在时间x停止。


0
投票

我们假设你希望你的代码每天晚上10点(22:oo)小时运行。如果您使用的是Linux,则可以执行以下操作以root用户身份运行作业

sudo crontab -e 
0 22 * * *  /path/to/directory/python my_code.py

你的python文件my_code.py可能是这样的

# python code to search pattern in a string using regex
import re

str1 = 'this is {new} string with [special] words.'

r = re.search(r'\{(.*?)\}', str1)
if r:
    found =r.group()
else:
    "No match found"

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