文章目录
一、定时
Python下实现定时任务的方式有很多种方式。下面介绍几种
循环sleep:
这是一种最简单的方式,在循环里放入要执行的任务,然后sleep一段时间再执行。缺点是,不容易控制,而且sleep是个阻塞函数。
def timer(n):
'''''
每n秒执行一次
'''
while True:
print time.strftime('%Y-%m-%d %X',time.localtime())
yourTask() # 此处为要执行的任务
time.sleep(n)
threading的Timer:
threading模块中的Timer能够帮助实现定时任务,而且是非阻塞的。
比如3秒后打印helloworld:
def printHello():
print "hello world"
Timer(3, printHello).start()
比如每3秒打印一次helloworld:
def printHello():
print "Hello World"
t = Timer(2, printHello)
t.start()
if __name__ == "__main__":
printHello()
使用sched模块:
sched是一种调度(延时处理机制)。
# -*- coding:utf-8 -*-
# use sched to timing
import time
import os
import sched
# 初始化sched模块的scheduler类
# 第一个参数是一个可以返回时间戳的函数,第二个参数可以在定时未到达之前阻塞。
schedule = sched.scheduler(time.time, time.sleep)
# 被周期性调度触发的函数
def execute_command(cmd, inc):
'''''
终端上显示当前计算机的连接情况
'''
os.system(cmd)
schedule.enter(inc, 0, execute_command, (cmd, inc))
def main(cmd, inc=60):
# enter四个参数分别为:间隔事件、优先级(用于同时间到达的两个事件同时执行时定序)、被调用触发的函数,
# 给该触发函数的参数(tuple形式)
schedule.enter(0, 0, execute_command, (cmd, inc))
schedule.run()
# 每60秒查看下网络连接情况
if __name__ == '__main__':
main("netstat -an", 60)
Scheduler:
-*- coding:utf_8 -*-
import os,schedule,time
def job():
cmd='taskkill /F /IM phantomjs.exe'
os.system(cmd)
schedule.every().day.at("00:00").do(job)
while True:
schedule.run_pending()
time.sleep(1)
二、进程
单次运行
代码如下(示例):
def printHello():
print "hello world"
Timer(3, printHello).start()
循环运行
代码如下(示例):
# -*- coding:utf_8 -*-
from threading import Timer
def job():
t = Timer(600, job)
t.start()
if __name__ == "__main__":
job()
三、关闭win程序
cmd='taskkill /F /IM Thunder.exe'
os.system(cmd)
四、打开win程序(win32api实现)
安装
在Python for Windows Extensions Files下载对应版本的pywin32,安装后能在C:\Users\Administrator\AppData\Local\Programs\Python\Python37\Lib\site-packages\win32找到对应的win32api.py文件,因此这样导入:
from win32 import win32api
运行
win32api.ShellExecute(0, 'open', 'notepad.exe', '', '', 0) # 后台执行
win32api.ShellExecute(0, 'open', 'notepad.exe', '', '', 1) # 前台打开
win32api.ShellExecute(0, 'open', 'notepad.exe', '1.txt', '', 1) # 打开文件
win32api.ShellExecute(0, 'open', 'http://www.sohu.com', '', '', 1) # 打开网页
win32api.ShellExecute(0, 'open', 'D:\\Opera.mp3', '', '', 1) # 播放视频
win32api.ShellExecute(0, 'open', 'D:\\hello.py', '', '', 1) # 运行程序