MSBA-341 · Lesson 8 of 12 · 19 min

Batch jobs and the SysOperation framework

▶ Video coming soon A video version of this lesson is on the way.

Lesson 4 left a loose end. When a casting line was created without a heat number, a data event handler queued an alert instead of sending it, because sending email inside the insert transaction would slow every purchase order and could fail for reasons that had nothing to do with purchasing. Something had to process that queue. Marisol also wanted a weekly report of open casting lines without certificates, and Thandeka wanted old alert records cleaned up after ninety days. All three are background processes, and the standard way to build them in finance and operations apps is the SysOperation framework running in batch.

Why a framework

A background process needs more than a method that does the work. It needs a way to collect parameters from the user, a dialog that shows those parameters, the ability to run now or to be scheduled in batch with recurrence, and a clear separation between the user interface and the logic so the logic can run on the server without one. Older X++ code used the RunBase and RunBaseBatch classes, which put all of this in one class. SysOperation splits it into separate classes with separate jobs, which makes the logic easier to test and reuse, and is Microsoft's recommended pattern for new development.

Six boxes. A menu item (action) points to the controller, which chooses the execution mode, and the controller points to the service operation that runs the work. The data contract with the parameters sits below the controller, with an optional UI builder dialog to its left. A dashed arrow from a batch server box to the service shows that in batch mode the work runs on the batch server.
The classes of a SysOperation process and how they relate.

The four parts

The SysOperation classes.
PartBase class or attributeJob
Data contractDataContractAttribute on the class, DataMemberAttribute on parm methodsHolds the parameters; each data member becomes a dialog field
ServiceSysOperationServiceBase (recommended) with a public methodDoes the work using the contract's values
ControllerSysOperationServiceControllerConnects the service method, shows the dialog, decides how the process runs
UI builder (optional)SysOperationAutomaticUIBuilderCustomizes the dialog: lookups, grouping, field behaviour

The data contract is a class decorated with the DataContract attribute. Each parameter is a parm method decorated with DataMember, and optionally with attributes that set its label, help text, display order and group. Because the contract is serialized when the process runs in batch, only members marked as data members survive the trip to the server. Prudence's first contract had a plain member variable for a date that she set in code; it was always empty in batch because it was never serialized.

A data contract with two parameters that appear as dialog fields in the stated order.
[DataContract, SysOperationContractProcessing(classStr(CRInspAlertUIBuilder))]
final class CRInspAlertContract
{
    int     maxAlerts;
    NoYesId includeWaived;

    [DataMember, SysOperationLabel(literalStr("@CRCustom:MaxAlerts")), SysOperationDisplayOrder('1')]
    public int parmMaxAlerts(int _maxAlerts = maxAlerts)
    {
        maxAlerts = _maxAlerts;
        return maxAlerts;
    }

    [DataMember, SysOperationLabel(literalStr("@CRCustom:IncludeWaived")), SysOperationDisplayOrder('2')]
    public NoYesId parmIncludeWaived(NoYesId _includeWaived = includeWaived)
    {
        includeWaived = _includeWaived;
        return includeWaived;
    }
}

The service class contains the business logic in a public method that takes the contract as its parameter. It should not depend on a user interface; it reads parameters from the contract, does its work, and records what happened. CRInspAlertService::process read unsent alerts from the CRInspAlertQueue table up to the maximum in the contract, built a message for each buyer through the standard email framework, marked each alert as sent in its own small transaction, and logged failures on the alert record so the next run could retry them.

The service processes one alert per transaction so a failure does not roll back alerts already sent.
final class CRInspAlertService extends SysOperationServiceBase
{
    public void process(CRInspAlertContract _contract)
    {
        CRInspAlertQueue queue;
        int processed;

        while select forupdate queue
            where queue.Status == CRInspAlertStatus::Pending
        {
            if (processed >= _contract.parmMaxAlerts())
            {
                break;
            }
            ttsbegin;
            CRInspAlertSender::send(queue);
            queue.Status = CRInspAlertStatus::Sent;
            queue.update();
            ttscommit;
            processed++;
        }
    }
}

The controller connects everything. It extends SysOperationServiceController and is constructed with the service class name, the method name and an execution mode. A static main method lets a menu item start it. The controller builds the dialog from the contract, and when the user selects OK it either runs the service immediately or, if the user turned on Batch processing in the dialog, creates a batch job with a task that will run the service on the batch server.

A controller started from an action menu item.
final class CRInspAlertController extends SysOperationServiceController
{
    public static void main(Args _args)
    {
        CRInspAlertController controller = new CRInspAlertController(
            classStr(CRInspAlertService),
            methodStr(CRInspAlertService, process),
            SysOperationExecutionMode::Synchronous);

        controller.parmDialogCaption("@CRCustom:SendInspectionAlerts");
        controller.startOperation();
    }
}

Execution modes

The execution mode decides how the service runs when the user does not choose batch. Synchronous runs the service in the user's session and the user waits; it suits short work where the user wants the result. Asynchronous runs it on the server without blocking the client, and the user is told when it ends. ReliableAsynchronous runs it through the batch framework as a job that runs once and is then removed, which gives the reliability of batch, including retries after a server restart, without the user having to schedule it. ScheduledBatch creates a batch job in the normal way. Whatever the default, the dialog's Batch processing option lets users schedule the operation with recurrence.

SysOperation execution modes.
ModeUser waitsUses batch frameworkTypical use
SynchronousYesNoShort actions where the result is needed immediately
AsynchronousNoNoLonger actions in the user's session that should not block
ReliableAsynchronousNoYes, as a one-time jobWork that must complete even if a server restarts
ScheduledBatchNoYesRecurring or scheduled work

Batch jobs, tasks and groups

A batch job is a container for one or more batch tasks, each of which runs one batch-enabled class. Tasks can have dependencies, so that task B starts only when task A has ended, ended with an error, or either. Each task belongs to a batch group, and administrators assign batch groups to batch servers, which lets heavy processing run on servers chosen for it. Jobs can have recurrence, such as every fifteen minutes or every Monday at 6:00, and alerts that notify a user when a job ends or fails.

Annelise set the alert job to run every fifteen minutes in the Cobalt Ridge batch group, with the maximum set to 500 alerts per run so a backlog after a long outage would clear over several runs rather than overwhelm email. The weekly report job ran on Mondays, and the cleanup job ran nightly. Each was created from the controller's dialog with the Batch processing option and recurrence, so no code was needed to schedule them.

Splitting work into parallel tasks

Large jobs can be faster if the work is split into several tasks that run at the same time on different threads or servers. The usual pattern is a top-level service that divides the records into bundles and adds one runtime task per bundle to its own batch job, each task running a worker service on its bundle. Microsoft's documentation describes bundling, individual task per record and top picking patterns, each with different trade-offs. Desmond showed the bundling pattern but did not use it for alerts, because 500 messages every fifteen minutes did not justify the complexity. He said parallelism belongs where measurements show a single task is too slow.

The UI builder

The automatic dialog is often enough. When it is not, a UI builder class extending SysOperationAutomaticUIBuilder can change it: add a custom lookup to a field, show or hide fields depending on other values, or validate entries before the dialog closes. The contract names its UI builder with the SysOperationContractProcessing attribute. CRInspAlertUIBuilder disabled the Include waived field unless the user was a member of the quality role, because only quality engineers needed alerts about waived lines.

When to use RunBaseBatch

Older standard processes still use RunBaseBatch, and some developers prefer it for small jobs because everything is in one class. For new Cobalt Ridge work, Desmond's rule was SysOperation. The exam expects candidates to know both exist, to recognize the SysOperation classes and attributes, and to choose an execution mode appropriate to the scenario. Extending a standard RunBaseBatch class follows the same Chain of Command rules as any other class: wrap its methods, call next, and add members through the extension.

Batch-safe code

Code that runs in batch has no user to answer a question, no dialog to show and no client to update. It also runs under the identity of the user who scheduled the job, so security applies, but in that user's context rather than whoever happens to be looking at the job. Prudence's checklist for batch-safe code was: never call Box or a dialog in the service; write results to tables or the batch job log through info messages, which are captured in the job's log; keep transactions small; make each unit of work safe to retry; and handle a company context explicitly with changecompany when processing data across legal entities.

Monitoring batch jobs

Once jobs run on a schedule, someone has to watch them. The batch jobs page shows each job's status, its tasks, its recurrence and its history. Each run's history includes the log, where info, warning and error messages written by the service are kept, so a service that writes clear messages for each problem record leaves an audit trail without extra tables. Jobs can raise alerts when they end, end with an error or are cancelled, and Annelise set the alert job to notify her and Desmond on errors. She also checked the job history each morning for the first two weeks after go-live, and then once a week.

Priorities and scheduling

Batch servers have a limited number of threads, and many jobs compete for them, from Microsoft's own system jobs to customer processes. Administrators control this through batch groups, the servers assigned to each group, and, in recent versions, priority-based scheduling, where jobs carry a scheduling priority that decides which waiting tasks start first. The details vary by version, so Annelise followed Microsoft's current documentation when she set them up. For Cobalt Ridge, the alert job had a normal priority, while the nightly master planning run, which several plants depended on, had a higher one.

Testing SysOperation services

Because the service class has no user interface, it is easy to test with the SysTest framework. A test class creates a contract, sets its parameters, inserts test data, calls the service method directly and checks the results. Prudence's tests for CRInspAlertService inserted three pending alerts, ran the service with a maximum of two, and asserted that exactly two were marked sent and one was still pending. A second test made the sender fail for one alert and asserted that the failure was logged on that alert and the others were still sent. The tests ran in a few seconds and did not need a batch server, because they called the service the same way the batch task would.

Extending standard batch processes

Developers often need to change a standard batch process rather than write a new one. If the process uses SysOperation, a Chain of Command extension of its data contract can add a new parameter, a wrapper on the service method can add work before or after the standard work, and an extension of the UI builder can change the dialog. If the process uses RunBaseBatch, its dialog, getFromDialog and pack and unpack methods usually need to be wrapped together to add a parameter, because RunBaseBatch stores parameters through its own packing pattern. Desmond warned that adding a member to a packed list without handling versions properly can make saved batch jobs fail to load after deployment, so this is an area for careful testing.

Choosing between batch and other options

Not every background need is a batch job. Events that external systems must react to belong in business events, so the other system is told immediately instead of polling. Work that must happen inside the same transaction as a user's change belongs in the change itself, kept short. Batch jobs suit work that can wait a few minutes, that processes many records, or that runs on a schedule. The alert queue sat in the middle: it was written inside the transaction, which was cheap, and sent from batch, which could wait. Desmond said that recognizing which part of a process needs to be immediate and which can wait is one of the most useful design habits a finance and operations developer can have.

Worked problem

Choosing an execution mode

Buyers want a button on the purchase order that immediately resends the inspection alert for the selected line. The resend takes under a second. The weekly report takes several minutes. Which modes should the two controllers use?

Show solution
  1. The resend is short, and the buyer wants to see that it worked, so Synchronous is appropriate.
  2. The weekly report takes minutes and runs on a schedule, so its controller can default to ScheduledBatch, and the recurrence is set by an administrator.
  3. If buyers sometimes run the report on demand, ReliableAsynchronous would run it in the background without blocking them and survive a restart.

Answer: Synchronous for the resend; ScheduledBatch for the recurring report, with ReliableAsynchronous for on-demand runs.

Common mistakes

  • MistakePutting a parameter in a contract member that is not a data member.

    InsteadMark every parameter parm method with DataMember so it is serialized for batch.

  • MistakeShowing dialogs or message boxes inside the service.

    InsteadKeep the service free of user interface code; it may run in batch.

  • MistakeProcessing thousands of records in one transaction.

    InsteadUse small transactions so one failure does not roll back completed work.

  • MistakeSplitting every job into parallel tasks.

    InsteadParallelize only where a single task is measurably too slow.

Summary and key terms

  • SysOperation separates a background process into a data contract, a service, a controller and an optional UI builder.
  • Contracts use DataContract and DataMember attributes; only data members are serialized for batch.
  • Controllers run services synchronously, asynchronously, reliably asynchronously or as scheduled batch.
  • Batch jobs contain tasks with dependencies, run in batch groups on chosen servers, and can recur.
  • Batch-safe code has no user interface, uses small transactions and is safe to retry.
SysOperation framework
The pattern of contract, service and controller classes for background processes.
Data contract
A class holding parameters, marked with DataContract and DataMember.
Controller
The SysOperationServiceController subclass that shows the dialog and starts the service.
Batch group
A grouping of batch tasks that administrators assign to batch servers.
ReliableAsynchronous
An execution mode that runs work through the batch framework as a one-time job.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Why did Prudence's date parameter arrive empty in batch?

    Show answer

    It was a plain member variable, not a data member, so it was not serialized.

  2. How did Cobalt Ridge prevent a backlog from overwhelming email?

    Show answer

    The contract limited each run to 500 alerts, so a backlog cleared over several runs.

  3. Which class customizes lookups in a SysOperation dialog?

    Show answer

    A UI builder extending SysOperationAutomaticUIBuilder.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz