How to Schedule a task programmatically

荒凉一梦 提交于 2021-02-06 04:42:38

问题


How can I schedule a task using delphi 7 like Google updater?
I'm not using the registry because it gets detected by Kaspersky antivirus as a false alarm.
Anything I add in the registry as a start-up item gets detected as a trojan so I decided to use task schedule


回答1:


The following piece of code shows how to delete and create the task which will run the application at system startup with system privileges. It uses the following command line:

However the Task Scheduler since Windows Vista supports force creation of tasks, I wouldn't use it for backward compatibility with Windows XP, where this flag doesn't exist. So the example below tries to delete the task (if already exists) and then create the new one.

It executes these commands:

schtasks /delete /f /tn "myjob"
schtasks /create /tn "myjob" /tr "C:\Application.exe" /sc ONSTART /ru "System"

/delete - delete the task
/f - suppress the confirmation
/create - create task parameter
/tn - unique name of the task
/tr - file name of an executable file
/sc - schedule type, ONSTART - run at startup
/ru - run task under permissions of the specified user

And here is the code:

uses
  ShellAPI;

procedure ScheduleRunAtStartup(const ATaskName: string; const AFileName: string;
  const AUserAccount: string);
begin
  ShellExecute(0, nil, 'schtasks', PChar('/delete /f /tn "' + ATaskName + '"'),
    nil, SW_HIDE);
  ShellExecute(0, nil, 'schtasks', PChar('/create /tn "' + ATaskName + '" ' +
    '/tr "' + AFileName + '" /sc ONSTART /ru "' + AUserAccount + '"'),
    nil, SW_HIDE);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  ScheduleRunAtStartup('myjob', 'C:\Application.exe', 'System');
end;



回答2:


Figured Out the problem here it works fine

Tested on windows 7 Pro if any one can test for me on XP PRO would b appreciated

procedure ScheduleRunAtStartup(const ATaskName: string; const AFileName: string;
  const GetPCName: string ; Const GetPCUser: String);
begin
  ShellExecute(0, nil, 'schtasks', PChar('/delete /f /tn "' + ATaskName + '"'),
    nil, SW_HIDE);
  ShellExecute(0, nil, 'schtasks', PChar('/create /tn "' + ATaskName + '" ' + '/tr "' + QuotedStr(AFileName) + '" /sc ONLOGON /ru "' + GetPCName+'\'+GetPCUser + '"'), nil, SW_HIDE)
end;


来源:https://stackoverflow.com/questions/8700709/how-to-schedule-a-task-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!