Modifier

Partager via


Task scheduler

The task scheduler enables you to control when certain operations or processes (in other words tasks) are run. Basically, a task is a codeunit or report that is scheduled to run at a specific date and time. Tasks run in a background session between the Dynamics 365 Business Central service instance and database. Behind the scenes, the task scheduler is used by the job queue to process job queue entries that are created and managed from the clients.

Note

Business Central supports multiple ways to run asynchronous (async) operations, such as job queues, scheduled tasks, new sessions, and page background tasks. Learn more in Async processing overview.

When to use scheduled tasks in AL

Here's a few scenarios where you might want to use a scheduled task

  • From AL, you can schedule code to run either using the task scheduler or by enqueuing a job queue entry. If you want users to be able to change the scheduling, use the job queue.
  • Sometimes in AL code, you want to change company and run code there. Maybe instead you can schedule a task to run the code in the other company?
  • If something isn't urgent/time critical (for example, can run at a lower priority), consider running it with a task.

Create and manage scheduled tasks in AL

A scheduled task is basically a codeunit that runs logic in a background session at a specific time. Optionally, you can create a second codeunit that contains the logic to handle the task if an error occurs for any reason. This codeunit is referred to as a failure codeunit.

In AL code, you create and manage the tasks by using the AL methods that are available for the TaskScheduler data type.

Method Description Learn more in ...
CreateTask Adds a task to run a codeunit at a specified date and time. TaskScheduler.CreateTask(Integer, Integer [, Boolean] [, String] [, DateTime] [, RecordId]) Method

TaskScheduler.CreateTask(Integer, Integer, Boolean, String, DateTime, RecordId, Duration) Method
SetTaskReady Sets a task to the Ready state. A task can't run until it's Ready. TaskScheduler.SetTaskReady(Guid [, DateTime]) Method
TaskExists Checks whether a specific task exists. TaskScheduler.TaskExists(Guid) Method
CancelTask Cancels a scheduled task. TaskScheduler.CancelTask(Guid) Method

To set up a task, create codeunits that contain the logic that you want to run at a scheduled time. Once you have the codeunits, add code to the application that calls the CreateTask method to schedule a task. The CreateTask method can also specify the earliest date to run the task.

How task scheduler works

This section describes the flow that a scheduled task goes through.

General flow

When a scheduled task is run, there are two possible execution paths that it can follow: the main path and the exception path. The main path is used to run the main codeunit and failure codeunits, if any. The exception path is used to handle errors and control the retry flow when errors occur in the main path. What happens in the exception path depends on whether the exception is retriable.

Here's a general overview of the process:

  1. When a task is created, the task is recorded in table 2000000175 Scheduled Task of the database.

  2. When task achieves the ready state and its scheduled time occurs, a new background session is started.

  3. The main path starts:

    1. The company is opened and the scheduled task in the table 2000000175 Scheduled Task is validated.

      If any error occurs during this phase, the task fails unless there's a failure codeunit. In which case, the failure code runs.

    2. The task's main codeunit is run:

      • If main codeunit runs successfully, it's removed from table 2000000175 Scheduled Task.
      • If an error occurs, the error is passed on to the exception path.
  4. The exception path starts:

    1. The transaction is rolled back.

    2. The exception handling logic is run:

      • If the exception is retriable, the main codeunit is rerun following the main path.

        This retry flow continues in the same session until the task succeeds or until the maximum number of retries is exceeded, then it fails. The session is then deleted. To understand when the task is retried, see Retry Intervals.

      • If the exception isn't retriable and there's no failure codeunit, the task fails.

      • If the exception isn't retriable and there's a failure codeunit, the current session is terminated. A new session is started, and the failure codeunit runs in this session, following the main path.

        If the failure codeunit doesn't handle the error or fails itself, then the exception path is run to retry the failure codeunit. This retry flow continues in the same session until the task succeeds or until the maximum number of retries is exceeded. The session is then terminated.

Detailed flow

The following diagram illustrates the flow in detail.

Shows the detailed flow of a scheduled task.

Retry intervals

When a task's main codeunit or failure codeunit enters the retry flow, it reruns at approximately the following intervals as long as the error persists. The number of retires and the intervals are different for Business Central online and on-premises.

Online

A codeunit is retried up to 99 times, according to the following intervals:

Retry attempt Wait time (minutes) after previous attempt
1 and 2 0.5
3 and 4 1
5 and 6 2
7 and 8 3
9 to 99 5

On-premises

A codeunit is retried up to nine times, according to the following intervals:

Retry attempt Wait time (minutes) after previous attempt
1 and 2 2
3 4
4 to 9 15

Error conditions and retriable exceptions

A task can fail under the various conditions, like:

  • The company can't be opened.
  • A SQL connection or transient error occurred with the database.
  • The Dynamics 365 Business Central service instance restarted while the task was being run.
  • An upgrade is in progress.

The task scheduler is designed to automatically rerun main and failure codeunits when certain exceptions occur, instead of just failing on the first attempt. Exceptions that cause the system to rerun a codeunit are referred to as retriable exceptions. Whether an exception is retriable depends on whether the exception occurs in the main or failure codeunit and if you're using Business Central online or on-premises.

Tip

If the same code needs to run both in the UI but also in the background (in a scheduled task or with a job queue entry) or in a web service call (SOAP/OData/API), then use if GuiAllowed() then calls to encapsulate AL code that interact with the user. Learn more in System.GuiAllowed() Method.

Retriable exceptions in the main codeunit

If you're running Business Central online, the service controls which exceptions are retriable. With Business Central on-premises, you can specify retriable exceptions by configuring the Execution Retry Exceptions (TaskSchedulerExecutionRetryExceptions) setting on the Business Central Server instance. The Execution Retry Exceptions setting is semicolon-separated list of exceptions in a format: Exception1;Exception2;Exception3. If you want to specify error code of the exception, use the following format instead: Exception1:ErrorCode1;Exception2:ErrorCode2.

Retriable exceptions in the failure codeunit

Because failure codeunits are designed for error situations, expect for a selected few, almost all exceptions while running failure codeunits are retriable. It doesn't matter if you're using Business Central online or on-premises. Even with on-premises, you can't specify retriable exceptions, like you can for main codeunits.

AL methods that throw nonretriable exceptions in background sessions

When running codeunits as scheduled tasks, you must make sure that the AL code doesn't assume the ability to interact with a user through the UI. You can use the GuiAllowed Method to suppress UI interactions.

Note

The server returns the following exception when trying to invoke a dialog UI through a web service call or in a background session: NavNCLCallbackNotAllowedException: Callback functions are not allowed.

Variables of the Dialog data type or any of the methods listed as dialog methods can cause "callback not allowed" exceptions when they're called from a web service call or a background session. The Message Method (Dialog) is the only method in this category that doesn't cause an exception.

The following table describes how dialog boxes are handled in a background or web service session, which has no UI.

Method that creates the dialog box Behavior
Dialog.Confirm - Dialog box is suppressed.
- The following error occurs on the Business Central instance: Business Central attempted to issue a client callback to show a confirmation dialog box.
Dialog.Error - Dialog box is suppressed.
- AL code execution ends.
- The error is logged to the event log of the Business Central instance.
- The error is added to the Comments field of the Session Event table.

Note: Stopping the main codeunit with Dialog.Error('') is considered a successful operation, so the failure codeunit isn't executed.
Dialog.Message - Dialog box is suppressed.
- The message is recorded in the event log of the computer that is running Business Central instance. The log entry has type Information and includes the context of the message.
Dialog.Open - Dialog box is suppressed.
- Dialog box text is not displayed or logged.

Other AL methods that you shouldn't use in web service endpoints or background sessions are:

  • Page.Run
  • Page.RunModal
  • Activate
  • Report.Run
  • Report.RunModal
  • Hyperlink
  • File.Upload
  • File.Download

You should also avoid operations on client-side Automation and .NET Framework interoperability objects.

About task sessions and permissions

The task runs in a background session, which means that there's no user interface. The behavior is similar to that of the StartSession method, where any dialog boxes that would normally appear are suppressed. Learn more about specific dialog boxes in StartSession method.

The session runs by using the same user/credentials that are used when calling AL code. The user must have appropriate permissions to the codeunit and any other objects that are associated with the operation of the codeunit.

Note

The delegated admins can't schedule tasks. They can test the job queues by making a copy of the job and running it once in the foreground, but not as a recurrent or scheduled task. Learn more about limitations for delegated admins in Restricted access to Business Central as delegated administrators.

Task scheduler and performance

Scheduled tasks or job queue entries that are set to run on a recurring schedule can impact the performance of Business Central under either of the following conditions:

  • They run too frequently.

    Consider how often the task or job needs to run. Especially for polling scenarios, you might have better and more performant ways to react, such as using webhooks.

  • They run heavy jobs while many users are also using Business Central.

    Consider running them outside working hours. This might decrease locking and deadlock issues both for users and for the task or job itself.

Operational limits for the task scheduler

The Business Central service has limits on how long time a background session can run and how many tasks you can run in parallel with the task scheduler. The background sessions that are started to process scheduled tasks don't have the same concurrency limit as those started by other methods.

For more information, see Asynchronous task limits.

Monitor and troubleshoot

Business Central offers two ways to monitor the flow of scheduled tasks: telemetry in Azure Application Insights and the Session Event table. These tools let you follow execution of a task, and investigate errors in failure codeunits.

Task scheduler telemetry in Azure Application Insights

You can set up Business Central to send telemetry traces to an Azure Application Insights resource in Azure. Once set up, telemetry data is sent to the resource as scheduled task moves through the flow. Learn more in:

Enable sending telemetry to Application Insights

Analyzing task scheduler telemetry

Session Event table

From the Business Central web client, you can open the Session Events table by adding table=2000000111 to the URL. For example: https://businesscentral.dynamics.com/?table=2000000111.

Configure task scheduler for Business Central on-premises

Business Central Server includes several settings related to task scheduler. These settings allow you to enable or disable task scheduler and manage tasks. Learn more in Configure Business Central Server - Task Scheduler.

Note

Task scheduler telemetry in Azure Application Insights also works for Business Central on-premises.

Characteristics of job queues and scheduled tasks

Job queues and scheduled tasks come with different characteristics as described in the following table:

Method to start a new asynchronous operation Characteristics
Task Queued up
Runs once
Any server in a cluster can start it
Survives server restarts
No logging in Business Central
Has telemetry.
No user interface for administration.
Job queue Scheduled
Supports recurrence
Any server in a cluster can start it
Survives server restarts
Logging of results in Business Central
Has telemetry.
Has a user interface for administration.

For more information, see Async processing overview

Task Scheduler Data Type
Analyzing Task Scheduler Telemetry
Job queue
Async processing overview
Performance Articles for Developers
Developing Extensions
Get Started with AL