Advertisement
Guest User

Untitled

a guest
May 23rd, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. # 实际执行任务的进程是 multiprocessing.Process 启动的,主进程会等待子进程结束并检查 exitcode 0.
  2. # 另外如果多次任务执行失败会重启操作系统。
  3.  
  4. # 实际用法:
  5. # with TaskHeartbeat(host_id, secret_key, task['id'], task['timeout']):
  6. # 实际任务
  7.  
  8. class TaskHeartbeat(threading.Thread):
  9.  
  10. def __init__(self, host_id, secret_key, task_id, timeout):
  11. super(TaskHeartbeat, self).__init__()
  12. self.setDaemon(True)
  13.  
  14. self.is_exit = False
  15. self.host_id = host_id
  16. self.secret_key = secret_key
  17. self.task_id = task_id
  18. self.timeout = timeout
  19.  
  20. def run(self):
  21. start_time = arrow.utcnow()
  22. timeout_time = start_time.replace(seconds=+self.timeout)
  23.  
  24. while not self.is_exit:
  25. if arrow.utcnow() > timeout_time:
  26. # TODO: 上报执行超时
  27. kill_child_processes(os.getpid())
  28. os._exit(123)
  29. return
  30.  
  31. # TODO: 上报心跳
  32. time.sleep(30)
  33.  
  34. def __enter__(self):
  35. self.start()
  36. return self
  37.  
  38. def __exit__(self, exc_type, exc_val, exc_tb):
  39. # 继续传播异常,外部会捕获并上报任务失败
  40. self.is_exit = True
  41. return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement