python通过thread模块支持多线程,语法也很简洁,现在通过一个实例来看一下python中的多线程:
import thread
import time
#保证只额外启动一个线程
isRunning=False
#启动的时间控制,测试时间是23点44分,所以定的是这个时间,可以用于指定定时任务的执行时间
timer_hour=23
timer_min=44
#额外其他一个线程处理任务
def another_thread():
print '[another_thread] is start...'
#声明使用全局变量isRunning
global isRunning
#for循环模拟任务执行
for i in range(3):
time.sleep(1)
print '[another_thread] time: %s ' % time.strftime('%Y-%m-%d %X',time.localtime())
print '[another_thread] Is Running: %s' % isRunning
#此处只是为了保证该任务一天只启动一次,一分不会超过60秒
time.sleep(60)
print '[another_thread] is end...'
#该状态只是为了保证该任务不会重复启动,当然对于任务可以设置一个超时时间,到时不结束自动终结
isRunning = False
if __name__ == '__main__':
while True:
now = time.localtime()
print '[main_thread] time: %s' % time.strftime('%Y-%m-%d %X',now)
print '[main_thread] Is Running: %s' % isRunning
if now.tm_hour==timer_hour and now.tm_min==timer_min and not isRunning:
#进入任务前即置为True状态,防止重复启动
isRunning = True
#python开启一个新的线程,从后面打印日志的情况可以知道,并不会影响主线程的运行
thread.start_new_thread(another_thread,())
time.sleep(1)
代码执行后如下:
C:\Users\Captain\Desktop>python task.py
[main_thread] time: 2013-07-31 23:44:56
[main_thread] Is Running: False
[another_thread] is start...
[main_thread] time: 2013-07-31 23:44:57[another_thread] time: 2013-07-31 23:44:57
[main_thread] Is Running: True[another_thread] Is Running: True
[main_thread] time: 2013-07-31 23:44:58[another_thread] time: 2013-07-31 23:44:58
[main_thread] Is Running: True[another_thread] Is Running: True
[main_thread] time: 2013-07-31 23:44:59[another_thread] time: 2013-07-31 23:44:59
[another_thread] Is Running: True[main_thread] Is Running: True
[main_thread] time: 2013-07-31 23:45:00
[main_thread] Is Running: True
[main_thread] time: 2013-07-31 23:45:01
[main_thread] Is Running: True
[main_thread] time: 2013-07-31 23:45:02
该实例很简单,可按照这个思路,应用于定时任务,心跳检测,守护进程等实际场景中