RunBackgroundtask.dpr 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. program RunBackgroundtask;
  2. {$APPTYPE CONSOLE}
  3. {$R *.res}
  4. uses
  5. SysUtils,
  6. Quick.Commons,
  7. Quick.Console,
  8. Quick.Threads;
  9. type
  10. TMyJob = class
  11. private
  12. fId : Integer;
  13. fName : string;
  14. public
  15. property Id : Integer read fId write fId;
  16. property Name : string read fName write fName;
  17. function DoJob : Integer;
  18. end;
  19. var
  20. i : Integer;
  21. backgroundtasks : TBackgroundTasks;
  22. myjob : TMyJob;
  23. { TMyJob }
  24. function TMyJob.DoJob : Integer;
  25. var
  26. a, b : Integer;
  27. begin
  28. cout('task %d doing job...',[fId],etInfo);
  29. Sleep(Random(1000));
  30. a := Random(100);
  31. b := Random(5) + 1;
  32. Result := a div b;
  33. cout('task %d result %d / %d = %d',[fId,a,b,Result],etSuccess);
  34. end;
  35. begin
  36. ReportMemoryLeaksOnShutdown := True;
  37. Console.LogVerbose := LOG_DEBUG;
  38. try
  39. { TODO -oUser -cConsole Main : Insert code here }
  40. backgroundtasks := TBackgroundTasks.Create(10);
  41. for i := 1 to 100 do
  42. begin
  43. myjob := TMyJob.Create;
  44. myjob.Id := i;
  45. myjob.Name := 'Task' + i.ToString;
  46. backgroundtasks.AddTask(
  47. procedure(task : ITask)
  48. begin
  49. cout('task %d started',[TMyJob(task['Job']).Id],etDebug);
  50. task.Result := TMyJob(task['Job']).DoJob;
  51. end
  52. ).SetParameter('Job',myjob,True
  53. ).WaitAndRetry(10,100
  54. ).OnRetry(
  55. procedure(task : ITask; aException : Exception; var vStopRetries : Boolean)
  56. begin
  57. if not aException.Message.Contains('Division by zero') then vStopRetries := True
  58. else cout('task "%s" retried %d/%d (%s)',[TMyJob(task['Job']).Name,task.NumRetries,task.MaxRetries,aException.Message],etWarning);
  59. end
  60. ).OnException(
  61. procedure(task : ITask; aException : Exception)
  62. begin
  63. cout('task %d failed (%s)',[TMyJob(task['Job']).Id,aException.Message],etError);
  64. end
  65. ).OnTerminated(
  66. procedure(task : ITask)
  67. begin
  68. cout('task %d finished result = %d',[TMyJob(task['Job']).Id,task.Result.AsInteger],etDebug);
  69. end
  70. ).Run;
  71. end;
  72. backgroundtasks.Start;
  73. cout('Running tasks in background!',etInfo);
  74. ConsoleWaitForEnterKey;
  75. coutFmt('Task gueue size = %d',[backgroundtasks.TaskQueued],etInfo);
  76. backgroundtasks.Free;
  77. cout('finished tasks!!!!',etInfo);
  78. except
  79. on E: Exception do
  80. Writeln(E.ClassName, ': ', E.Message);
  81. end;
  82. end.