Delphi 为什么我的应用程序在从Windows计划程序运行时会冻结?

Delphi 为什么我的应用程序在从Windows计划程序运行时会冻结?,delphi,Delphi,我有一个简单的应用程序: uses SysUtils; {$R *.res} procedure Log(text: string); var myFile: textfile; begin AssignFile(myFile, 'my.log'); if not(FileExists('my.log')) then Rewrite(myFile) else Append(myFile); Writeln(myFile, text); CloseF

我有一个简单的应用程序:

uses
  SysUtils;

{$R *.res}

procedure Log(text: string);
var
  myFile: textfile;
begin
  AssignFile(myFile, 'my.log');
  if not(FileExists('my.log')) then
    Rewrite(myFile)
  else
    Append(myFile);
  Writeln(myFile, text);
  CloseFile(myFile);
end;

begin
    Log(TimeToStr(Now)+' Passed!');
end.
当我试图通过Windows任务计划程序启动此应用程序时,我遇到了一个问题。
计划任务的状态为“正在运行”,但未发生任何事件。

您需要提供保存文件的完整路径。当Windows任务调度器启动应用程序时,应用程序的工作目录将位于任务调度器应用程序所在的任何位置。反过来,Windows不允许应用程序在该位置保存文件。因此,您必须准确地告诉它保存文件的位置

procedure Log(text: string);
var
  myFile: textfile;
  Filename: String;
begin
  Filename:= IncludeTrailingBackslash(ExtractFilePath(ParamStr(0)))+'my.log';
  AssignFile(myFile, Filename);
  if not(FileExists(Filename)) then
    Rewrite(myFile)
  else
    Append(myFile);
  Writeln(myFile, text);
  CloseFile(myFile);
end;

我假设Windows因为您的标题“冻结”而拒绝访问。尽管如此,即使问题没有被拒绝访问,您仍然不知道该位置在哪里。

您确实应该使用完整的路径。现在,您不知道该文件是在哪个文件夹中创建的。您可能遇到IO异常,并且您的程序没有退出。是哪个用户运行该应用程序。它可能正在会话0中运行。您需要向任务提供凭据才能在桌面上看到它。我假设访问被拒绝,因为无论应用程序在哪里调用,这都将位于系统位置。您是否已在系统驱动器中搜索文件
my.log
?在“closefile”之前添加“flush(myfile)”,Jerry,提醒:写入存储exe的文件夹是有风险的,因为根据安全级别和Windows版本,可能会禁止写入。将其存储到限制较少的文件夹(可能在AppData或Documents中)不是更安全吗?@Robert是的,这是我想说的重点,但保存文件的位置并不取决于我,我回答这个问题是为了满足OP的特定需要,匹配他们的原始代码,这表明他们希望将其保存在那里。