forked from OxOOo/ProxyPoolWithUI
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
91 lines (79 loc) · 2.83 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# encoding: utf-8
import sys, os, signal
sys.path.append(os.path.dirname(__file__) + os.sep + '../')
from multiprocessing import Process
import time
from proc import run_fetcher, run_validator
from api import api
import multiprocessing
# 进程锁
proc_lock = multiprocessing.Lock()
class Item:
def __init__(self, target, name):
self.target = target
self.name = name
self.process = None
self.start_time = 0
def main():
processes = []
processes.append(Item(target=run_fetcher.main, name='fetcher'))
processes.append(Item(target=run_validator.main, name='validator'))
processes.append(Item(target=api.main, name='api'))
while True:
for p in processes:
if p.process is None:
p.process = Process(target=p.target, name=p.name, daemon=False, args=(proc_lock, ))
p.process.start()
print(f'启动{p.name}进程,pid={p.process.pid}')
p.start_time = time.time()
for p in processes:
if p.process is not None:
if not p.process.is_alive():
print(f'进程{p.name}异常退出, exitcode={p.process.exitcode}')
p.process.terminate()
p.process = None
# 解除进程锁
try:
proc_lock.release()
except ValueError:
pass
elif p.start_time + 60 * 60 < time.time(): # 最长运行1小时就重启
print(f'进程{p.name}运行太久,重启')
p.process.terminate()
p.process = None
# 解除进程锁
try:
proc_lock.release()
except ValueError:
pass
time.sleep(0.2)
def citest():
"""
此函数仅用于检查程序是否可运行,一般情况下使用本项目可忽略
"""
processes = []
processes.append(Item(target=run_fetcher.main, name='fetcher'))
processes.append(Item(target=run_validator.main, name='validator'))
processes.append(Item(target=api.main, name='api'))
for p in processes:
assert p.process is None
p.process = Process(target=p.target, name=p.name, daemon=False)
p.process.start()
print(f'running {p.name}, pid={p.process.pid}')
p.start_time = time.time()
time.sleep(10)
for p in processes:
assert p.process is not None
assert p.process.is_alive()
p.process.terminate()
if __name__ == '__main__':
try:
if len(sys.argv) >= 2 and sys.argv[1] == 'citest':
citest()
else:
main()
sys.exit(0)
except Exception as e:
print('========FATAL ERROR=========')
print(e)
sys.exit(1)