How to do it...

  1. Open your AL project in Visual Studio Code.
  2. In Explorer, create a new file named A Simple Task.al, and in Editor, create a new codeunit object:
codeunit 50109 "A Simple Task"
{

}
  1. We're going to create a very simple function that will just record the date and time that the task is executed. Definitely not fancy, but it'll get the job done!

Add the following code to the codeunit:

trigger OnRun()
begin
SimpleTaskFunction();
end;

local procedure SimpleTaskFunction()
var
SimpleTaskResult: Record "Simple Task Result";
begin
SimpleTaskResult.UpdateWithNewRun();
end;
A scheduled task can be configured to run a codeunit, but not a specific function within a codeunit. This is why you will need to create a new codeunit with an onRun() trigger, where you can then define what function(s) you want to run when the task executes.
  1. Now, let's add a function to create a new task:
procedure AddTaskToScheduler()
begin
TaskScheduler.CreateTask(Codeunit::"A Simple Task", 0, false,
'', CurrentDateTime());
end;
  1. And let's add a function to delete a scheduled task:
procedure DeleteTaskFromScheduler(TaskID: Guid)
begin
TaskScheduler.CancelTask(TaskID);
end;
  1. A task will not be executed until it is marked as Ready. You can set that when the task is created or you can have a separate function to let the user decide when the task is ready. 

For our example, let's create a function to mark the task as ready for processing:

procedure SetTaskToReady(TaskId: Guid)
begin
TaskScheduler.SetTaskReady(TaskId);
end;

Alrighty, we've built our code so let's try it out! Press F5 to build and publish your application:

  1. Use the  icon and search for Scheduled Task Example. Click on it to launch the page.
  2. Use the actions on the page to create a few tasks.
  3. Note that even if you wait a few minutes, the tasks will not disappear when you select Actions | Refresh Page. This is because the tasks are not ready to be processed.
  4. Select one of your tasks and choose Actions | Set Task to Ready.
  5. Press Actions | Refresh Page. It may take a few moments but the record you marked as Ready will disappear and the result should get updated to reflect when the task was completed, like so: 

You may find you have to wait a few moments for the data to be updated, so you might have to click the button a few times. Remember though, these scheduled tasks don't have a guaranteed start time. They will be executed when the task scheduler is finished with all previous tasks, so small delays like this are to be expected.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.37.20