The Task Scheduling service supports multiple job types, such as simple jobs and cluster jobs. You can choose a job type based on your business needs. This topic uses a simple job as an example to show you how to quickly develop a simple job locally and configure it in the console.
For a sample Task Scheduling project, you can download the sample project.
Procedure
Develop the local application.
Create a SOFABoot project.
Download and configure a SOFABoot project prototype. For more information about the configuration steps, see Quick Start.
NoteThe Task Scheduling client supports development using the SOFABoot framework or other Maven project frameworks. This topic uses SOFABoot as an example. For information about how to configure non-SOFABoot projects, see Non-SOFABoot Projects.
Import the Task Scheduling dependencies.
In the SOFABoot project, import the Task Scheduling dependency:
<dependency> <groupId>com.alipay.sofa</groupId> <artifactId>scheduler-enterprise-sofa-boot-starter</artifactId> </dependency>For SOFABoot versions earlier than 3.4.3, add the following Tracer dependency.
NoteBefore you add the dependency, check whether the project already has a dependency on Tracer to avoid JAR package conflicts.
SOFABoot 3.4.3 and later versions automatically include the Tracer dependency. You do not need to add it manually. For more information about the latest SOFABoot versions, see SOFABoot Version Guide.
<dependency> <groupId>com.alipay.sofa</groupId> <artifactId>tracer-enterprise-sofa-boot-starter</artifactId> </dependency>
Modify global configuration items.
In the
application.propertiesfile, configure the global middleware settings. For more information, see properties configuration items.You can implement the processor interface.
The client provides the
ISimpleJobHandlerinterface. Implement this interface to write your business logic code./** * Simple job handler interface. */ public interface ISimpleJobHandler extends IJobHandler{ /** * Handles the request. * * @param context * @return */ ClientCommonResult handle(JobExecuteContext context); }Code description:
JobExecuteContextis the request context for the triggered job. You can retrieve job information from this context. For example, use thegetCustomParam(String key)method to retrieve the custom parameters set in the console.If sharding is set for the job, use the
getSharding()method to obtain the shard number assigned to the current machine. For more information, view the source code of thecom.alipay.antschedulerclient.model.JobExecuteContextclass.
Implementation class.
The class must implement the
handle,getThreadPool, andgetNamemethods.handle: Executes the business logic in this method.getThreadPool: Retrieves a thread pool to execute the job. If you do not set a thread pool, the client's default thread pool is used.getName: Retrieves the name of this executor. When the client receives a job trigger request, it looks for a matching executor by name.NoteIf a job needs to be executed in multiple steps, you can write multiple implementation classes and enable stepped execution in the console.
The following code provides an example:
public class AlwaysSuccessHandler implements ISimpleJobHandler{ private static final String NAME ="ALWAYS_SUCCESS_JOB"; private static final ThreadPoolExecutor executor =new ThreadPoolExecutor(20, 300,1,TimeUnit.HOURS,new ArrayBlockingQueue<Runnable>(100){}) /** * Handles the business logic. **/ @Override public ClientCommonResult handle(JobExecuteContext context) throws InterruptedException{ // Get custom parameters. Integer num =(Integer) context.getCustomParam("num"); if(num ==null){ num =0; } num = num +1; // Update the custom parameters. context.putCustomParams("num",5); return ClientCommonResult.buildSuccessResult(); } @Override public ThreadPoolExecutor getThreadPool(){ // Use a custom implementation class. return executor; } @Override public String getName(){ // The handler name. The handler configured on the management page is defined here. return NAME; } }
Configure Spring.
Configure the interface implementation class as a Spring Bean in one of the following ways:
Configure it in the
src/main/resources/META-INF/xxx/xxx-xxx.xmlfile. The following code provides an example:<bean id="sampleService" class="com.antcloud.demo.antscheduler.service.SampleServiceImpl"/>Declare the Bean using the annotation-driven method.
Publish the application in the cloud.
After you develop the local client, publish and deploy it to the SOFAStack classic application service. For more information, see Publish and deploy applications.
Configure the scheduling job in the console.
Log on to the Task Scheduling console.
In the navigation pane on the left, choose Middleware > Task Scheduling > Task Configuration.
Choose Add Job > Simple Job, and then configure the following parameters:
Parameter
Description
Job Name
The name of the job. It is used to identify the job.
Application Name
Enter or select the target application name.
The name must be the same as the application name configured for
spring.application.namein theapplication.propertiesfile of the project.Scheduling Type
The scheduling type of the job. Valid values:
CRON expression trigger: This type of job is triggered at scheduled times based on a CRON expression.
Event trigger: This type of job is triggered by external events.
One-time trigger: This type of job is also triggered at a scheduled time based on a CRON expression, but it can be executed only once.
CRON Expression
The CRON expression used to trigger the job at scheduled times. For information about how to configure the expression, see CRON expression details.
This parameter is required only when Scheduling Type is set to CRON expression trigger.
Job Group (optional)
Select or create a job group to categorize and manage jobs.
Executor Name
Must be the same as the job handler name in the code. This is the executor name obtained by the
getNamemethod in the Implement the class step.Enable Sharding
Specifies whether to enable sharding for the job:
If you do not enable sharding, the job is scheduled to only one client server for execution.
If you enable sharding and set the number of shards to N, the job is triggered on N client servers for concurrent execution.
If you enable sharding, you must also implement job sharding in your local project code. For sample code, see Sample code for job sharding below.
Custom Parameters (optional)
Custom parameters let you pass parameters to a job from the console. Parameters can also be passed between jobs. The format is
key=value.Parameter configuration instructions:
Parameter Name: The name of the custom parameter.
It can contain uppercase letters, lowercase letters, digits, and underscores (_). The name cannot exceed 128 characters.
Type and Parameter Value: The available types and their value configurations are as follows.
STRING: Supports general strings.
LIST: Supports string arrays, such as
["aaa","bbb"].BOOLEAN: Supports true or false.
PLACEHOLDER: Supports parameter substitution. The following variables are currently supported:
${sharding}: Replaces the current shard value. Use with simple jobs.${shardingCount}: Replaces the number of shards configured for the simple job.${triggerTime}: Replaces the expected trigger time.
NoteYou can also get and overwrite custom parameters on the business side through the context object. The object must implement Serializable. For sample code, see Sample code for getting and overwriting custom parameters below.
Routing Policy
The routing policy for job execution. Valid values:
Random: Each execution is randomly distributed to a client server.
Directed: Each execution is distributed to the same client server.
You cannot specify the client server IP address.
Polling: Each execution is distributed to each client server in turn.
Communication Mode
The communication mode for the job. Valid values:
One-way ONEWAY: A one-way operation with no return value. The console does not record trigger history. Timeouts and retries are not supported.
Use this mode for high-frequency, non-critical jobs.
Callback CALLBACK: A bidirectional operation with a return value. You can view trigger history, set timeouts, and configure retries in the console.
Use this mode for critical jobs. The trigger interval must be at least 5 minutes.
Job Mutex
Specifies whether to enable job mutex mode. When job mutex mode is enabled, a job that is in the "Executing" or "Paused" state cannot be triggered again, even if the next trigger time is reached. The status of this scheduled execution is marked as "Skipped". By default, this feature is disabled.
This parameter can be configured only when Communication Mode is set to Callback CALLBACK.
Missed Trigger Policy
The policy for handling missed job triggers. Valid values:
Ignore: No compensatory action is taken.
Trigger Immediately: The job is retriggered immediately.
Trigger When Time is Sufficient: Whether to perform a compensatory trigger depends on whether there is enough time before the next trigger. If `Current Time + Timeout Period < Next Trigger Time`, a compensatory trigger is performed and recorded in the trigger history. Otherwise, the job is not triggered. If multiple triggers are missed, only one compensatory trigger is performed during recovery.
This parameter can be configured only when Communication Mode is set to Callback CALLBACK and Scheduling Type is set to CRON expression trigger.
Timeout Policy
The policy for handling job execution timeouts. Valid values:
Do Not Process: The statuses of the trigger record and the execution record are both marked as failed.
Retry Based on Failure Policy: The status of the current scheduled execution is marked as failed, and a retry is performed based on the Failure Handling Policy. After the retry, the record for this scheduled execution is reset to the retry result.
Stop Subsequent Triggers: The execution record status is "Failed", and the trigger record status is "Timeout". The job cannot be triggered again. This option is available only when job mutex mode is enabled.
This parameter can be configured only when Communication Mode is set to Callback CALLBACK.
Timeout Period
The timeout period for job execution. If the job does not return a callback within this period, the execution is considered failed. The unit can be Minute or Hour.
This parameter can be configured only when Communication Mode is set to Callback CALLBACK.
Failure Handling Policy
The policy for handling failed job executions. Valid values:
Do Not Retry: No retry is performed after a failure.
Retry up to Three Times: A retry is performed immediately after a failure, up to a maximum of three times.
Retry Until Next Trigger: Retries are performed immediately after a failure until the next trigger time.
Priority
Used to identify the importance of the job. It has no other function at present.
The default value is Medium.
Description (optional)
The description of the job, such as its business meaning and scope of impact. The description can be up to 1024 characters long.
Sample code for job sharding
public class ShardingSchedule implements ISimpleJobHandler { private final Logger LOGGER = LoggerFactory.getLogger(ShardingSchedule.class); private ThreadPoolExecutor threadPool; @Override public String getName() { return "SHARDING_SCHEDULE"; } @Override public ClientCommonResult handle(JobExecuteContext jobExecuteContext) throws Exception { int sharding = jobExecuteContext.getSharding(); // The number of shards obtained by the current machine LOGGER.info("current machine sharding is " + sharding); // The total number of shards System.out.println("total sharding num is " + jobExecuteContext.getShardingCount()); System.out.println("activity sharding is" + jobExecuteContext.getActivitySharding()); return ClientCommonResult.buildSuccessResult(); } @Override public ThreadPoolExecutor getThreadPool() { return threadPool; } /** * Setter method for property threadPool. * * @param threadPool value to be assigned to property threadPool */ public void setThreadPool(ThreadPoolExecutor threadPool) { this.threadPool = threadPool; } }Sample code for retrieving and overwriting custom parameters
public class SimpleTaskDemo implements ISimpleJobHandler { @Override public ClientCommonResult handle(JobExecuteContext context) { // Get the obj by key Object obj = context.getCustomParam("intObj"); // Get custom parameters Map<String, Object> paramsMap = context.getCustomParams(); context.putCustomParams("num", 2); List<String> listparam = newArrayList <>(); listparam.add("aaaaaa"); listparam.add("111111"); context.putCustomParams("intparam", 111); context.putCustomParams("stringparam", "dfadsfad1243"); context.putCustomParams("listparam", listparam); // Note: The object must implement Serializable context.putCustomParams("objectParam", newObject()); return ClientCommonResult.buildSuccessResult(); } .... }Click Submit.
In the job list, turn on the Enable switch for the target job.
If a client is online, it automatically registers for the newly configured job. When the job is disabled, you can also click Trigger in the Actions column to manually trigger the job once.

View job scheduling records
In the job list, click the name of the target job.
Click the Scheduling Records tab to view the scheduling records.
Scheduling records are retained for a maximum of 7 days. You can use the drop-down list above the tab to filter scheduling records by type, such as all records, successful executions, failed executions, and missed schedules.