test_addtask.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import pythoncom, sys, os, time, win32api
  2. from win32com.taskscheduler import taskscheduler
  3. task_name='test_addtask.job'
  4. ts=pythoncom.CoCreateInstance(taskscheduler.CLSID_CTaskScheduler,None,
  5. pythoncom.CLSCTX_INPROC_SERVER,taskscheduler.IID_ITaskScheduler)
  6. tasks=ts.Enum()
  7. for task in tasks:
  8. print(task)
  9. if task_name in tasks:
  10. print('Deleting existing task '+task_name)
  11. ts.Delete(task_name)
  12. t=ts.NewWorkItem(task_name)
  13. t.SetComment('rude comments')
  14. t.SetApplicationName(sys.executable)
  15. t.SetPriority(taskscheduler.REALTIME_PRIORITY_CLASS)
  16. t.SetParameters('-c"import win32ui,time;win32ui.MessageBox(\'hey bubba I am running\');"')
  17. t.SetWorkingDirectory(os.path.dirname(sys.executable))
  18. t.SetCreator('test_addtask.py')
  19. t.SetMaxRunTime(20000) #milliseconds
  20. t.SetFlags(taskscheduler.TASK_FLAG_INTERACTIVE|taskscheduler.TASK_FLAG_RUN_ONLY_IF_LOGGED_ON)
  21. ## |taskscheduler.TASK_FLAG_DELETE_WHEN_DONE) #task self destructs when no more future run times
  22. t.SetAccountInformation(win32api.GetUserName(),None)
  23. ## None is only valid for local system acct or if task flags contain TASK_FLAG_RUN_ONLY_IF_LOGGED_ON
  24. t.SetWorkItemData('some binary garbage')
  25. run_time = time.localtime(time.time() + 60)
  26. tr_ind, tr=t.CreateTrigger()
  27. tt=tr.GetTrigger()
  28. ## flags default to TASK_TRIGGER_FLAG_DISABLED (4)
  29. tt.Flags=taskscheduler.TASK_TRIGGER_FLAG_KILL_AT_DURATION_END
  30. tt.BeginYear=int(time.strftime('%Y',run_time))
  31. tt.BeginMonth=int(time.strftime('%m',run_time))
  32. tt.BeginDay=int(time.strftime('%d',run_time))
  33. tt.StartMinute=int(time.strftime('%M',run_time))
  34. tt.StartHour=int(time.strftime('%H',run_time))
  35. tt.MinutesInterval=1
  36. tt.MinutesDuration=5
  37. tt.TriggerType=taskscheduler.TASK_TIME_TRIGGER_MONTHLYDATE
  38. #months can contain multiples in a bitmask, use 1<<(month_nbr-1)
  39. tt.MonthlyDate_Months=1<<(int(time.strftime('%m',run_time))-1) ## corresponds to TASK_JANUARY..TASK_DECEMBER constants
  40. #days too
  41. tt.MonthlyDate_Days=1<<(int(time.strftime('%d',run_time))-1)
  42. tr.SetTrigger(tt)
  43. print(t.GetTriggerString(tr_ind))
  44. pf=t.QueryInterface(pythoncom.IID_IPersistFile)
  45. pf.Save(None,1)