python定时启动脚本
时间: 2023-08-29 09:05:45 浏览: 107
好的,你可以使用 Python 的 `schedule` 模块来创建定时任务,具体方法如下:
1. 导入 `schedule` 模块:
```python
import schedule
import time
```
2. 编写需要定时执行的函数:
比如以下是一个打印当前时间的函数。
```python
def job():
print("I'm running on", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
```
3. 使用 `schedule` 模块的 `schedule.every().[time_unit].do(job)` 方法来创建定时任务:
比如以下代码可以每隔一分钟执行一次 `job` 函数。
```python
schedule.every(1).minutes.do(job)
```
更多的时间单位和用法可以参考 `schedule` 模块的官方文档。
4. 使用 `while` 循环来执行定时任务:
```python
while True:
schedule.run_pending()
time.sleep(1)
```
完整代码如下:
```python
import schedule
import time
def job():
print("I'm running on", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
schedule.every(1).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)
```
这样就可以实现定时启动 Python 脚本了。
阅读全文
相关推荐















