I_d*_*hon 11 python python-3.x
我有一个生成 GUI 的主要 python 脚本,通过该 GUI,我希望用户能够创建、修改和删除由 Windows 任务计划程序管理的计划。
小智 11
只是为了完善此处的选项列表...仅调用 Windows 命令行怎么样?
import os
os.system(r'SchTasks /Create /SC DAILY /TN "My Task" /TR "C:mytask.bat" /ST 09:00')
Run Code Online (Sandbox Code Playgroud)
您可以启动任何可执行文件、批处理文件,甚至另一个 python 脚本 - 假设系统设置为执行 python...
schtasks 具有丰富的选项和功能列表... https://learn.microsoft.com/en-us/windows/win32/taskschd/schtasks
此代码创建一个将在 5 分钟内运行的任务(使用pywin32):
import datetime
import win32com.client
scheduler = win32com.client.Dispatch('Schedule.Service')
scheduler.Connect()
root_folder = scheduler.GetFolder('\\')
task_def = scheduler.NewTask(0)
# Create trigger
start_time = datetime.datetime.now() + datetime.timedelta(minutes=5)
TASK_TRIGGER_TIME = 1
trigger = task_def.Triggers.Create(TASK_TRIGGER_TIME)
trigger.StartBoundary = start_time.isoformat()
# Create action
TASK_ACTION_EXEC = 0
action = task_def.Actions.Create(TASK_ACTION_EXEC)
action.ID = 'DO NOTHING'
action.Path = 'cmd.exe'
action.Arguments = '/c "exit"'
# Set parameters
task_def.RegistrationInfo.Description = 'Test Task'
task_def.Settings.Enabled = True
task_def.Settings.StopIfGoingOnBatteries = False
# Register task
# If task already exists, it will be updated
TASK_CREATE_OR_UPDATE = 6
TASK_LOGON_NONE = 0
root_folder.RegisterTaskDefinition(
'Test Task', # Task name
task_def,
TASK_CREATE_OR_UPDATE,
'', # No user
'', # No password
TASK_LOGON_NONE)
Run Code Online (Sandbox Code Playgroud)
有关任务及其属性的更多信息,请访问:https : //docs.microsoft.com/en-us/windows/desktop/taskschd/task-scheduler-objects
PyWin32 提供了任务计划程序的接口win32com.taskscheduler。您可以在此处查看其使用示例:
@FredP 还链接了一个更简单的好例子:
wmi 模块的说明书中还有一个关于调度作业的有趣花絮,尽管它似乎没有使用任务调度程序:
我还需要一种使用 Python 在 Windows 10 中安排任务的方法。我发现了一些更简单的方法,仅使用subprocessPowerShell 的Scheduled Tasks cmdlets,它更强大,因为它可以让您更好地控制要安排的任务。
而且这个不需要第三方模块。
import subprocess
# Use triple quotes string literal to span PowerShell command multiline
STR_CMD = """
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "C:\\path\\to\\file.ps1"
$description = "Using PowerShell's Scheduled Tasks in Python"
$settings = New-ScheduledTaskSettingsSet -DeleteExpiredTaskAfter (New-TimeSpan -Seconds 2)
$taskName = "Test Script"
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddSeconds(10)
$trigger.EndBoundary = (Get-Date).AddSeconds(30).ToString("s")
Register-ScheduledTask -TaskName $taskName -Description $description -Action $action -Settings $settings -Trigger $trigger | Out-Null
"""
# Use a list to make it easier to pass argument to subprocess
listProcess = [
"powershell.exe",
"-NoExit",
"-NoProfile",
"-Command",
STR_CMD
]
# Enjoy the magic
subprocess.run(listProcess, check=True)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11310 次 |
| 最近记录: |