python定时重启程序

该博客主要介绍Python相关操作。包括实现定时任务的多种方式,如循环sleep、threading的Timer、使用sched模块等;还涉及进程的单次和循环运行,以及关闭和打开Windows程序的方法,打开程序通过win32api实现,并说明了安装步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


一、定时

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) # 运行程序
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值