如何在Python中运行18小时的脚本?

2024-04-25 12:36:57 发布

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

if __name__=='__main__':

print("================================================= \n")

print 'The test will be running for: 18 hours ...'
get_current_time = datetime.now()

test_ended_time = get_current_time + timedelta(hours=18)

print 'Current time is:', get_current_time.time(), 'Your test will be ended at:', test_ended_time.time()

autodb = autodb_connect()
db = bw_dj_connect()

started_date, full_path, ips = main()



pid = os.getpid()

print('Main Process is started and PID is: ' + str(pid))

start_time = time.time()

process_list = []

for ip in ips:
    p = Process(target=worker, args=(ip, started_date, full_path))
    p.start()
    p.join()
    child_pid = str(p.pid)
    print('PID is:' + child_pid)
    process_list.append(child_pid)

child = multiprocessing.active_children()
print process_list

while child != []:
    time.sleep(1)
    child = multiprocessing.active_children()


print ' All processes are completed successfully ...'
print '_____________________________________'
print(' All processes took {} second!'.format(time.time()-start_time))

我有一个python测试脚本,应该运行18个小时,然后自杀。该脚本对多个设备使用多处理。我从main()函数获取的数据将随时间而改变。你知道吗

我将这三个参数传递给多重处理中的worker方法。你知道吗

我怎样才能做到这一点?你知道吗


Tags: testchildgettimeismaincurrentprocess
2条回答

如果您不需要担心子进程的清理太多,您可以使用.terminate()杀死它们

...
time.sleep(18 * 60 * 60) # go to sleep for 18 hours
children = multiprocessing.active_children()
for child in children:
    child.terminate()

for child in multiprocessing.active_children():
    child.join() # wait for the children to terminate

如果您确实需要在所有子进程中进行一些清理,那么您需要修改它们的run循环(我假设while True),以监视时间的流逝,并且在主程序中只使用上面的第二个while循环,等待子进程自己离开。你知道吗

你从不比较日期时间.now()测试时间。你知道吗

# check if my current time is greater than the 18 hour check point.
While datetime.now() < test_ended_time and multiprocessing.active_children():
    print('still running my process.')

sys.exit(0)

相关问题 更多 >