How to Build a User‑Customizable Scheduled Task System with Java’s ScheduledExecutor
This article explains how to design and implement a user‑customizable scheduled‑task component in Java, addressing the limitations of open‑source frameworks by separating task creation, loading, scheduling, and execution, and provides practical code examples for robust backend task management.
Background
In many business scenarios users need to create a large number of custom scheduled tasks. Open‑source frameworks such as XXL‑JOB or Quartz are designed for developers, not for exposing task creation to end users.
Problems with Existing Frameworks
Integrating user‑defined tasks into the standard lifecycle of these frameworks is complex.
Frameworks decouple task management from business containers, requiring reverse calls from business services to the task center.
They assume clear execution strategies and stable task definitions, which is not true for frequently modified user tasks.
They lack a user‑friendly configuration UI.
Design Goals
Start/Stop Control : Distinguish between business task creation and job task creation, only loading tasks that users have marked for execution.
User‑Friendly Scheduling : Provide a UI for users to set scheduling strategies and times, internally converting them to Cron expressions.
Execution Window : Allow users to specify a time range during which the task may run.
Implementation Overview
The component follows the classic lifecycle: creation → loading → scheduling → execution . It is built on Java’s ScheduledExecutorService and mimics the architecture of XXL‑JOB.
Task Creation
Business tasks and job tasks are linked so that users decide when a task becomes active.
Task Loading
Loading uses ScheduledThreadPoolExecutor.scheduleAtFixedRate to periodically refresh the task cache. Unlike continuous polling, user‑defined tasks are usually pre‑created, and loading respects both start and end times.
// Upload and load definitions (local or DB)
uploadAndLoadDefinition();
// Initialize scheduling thread
internalScheduledExecutor.scheduleAtFixedRate(new SpringTaskMonitor(), 10, 45, TimeUnit.SECONDS);
// Definition maintenance thread
internalScheduledExecutor.scheduleAtFixedRate(new SpringTaskDefinitionMonitor(), 1, 2, TimeUnit.MINUTES);Task Scheduling
The scheduler checks each loaded task for validity, expiration, and execution window before submitting it to the execution pool.
public class SpringTaskMonitor implements Runnable {
private static Date DATE_INIT = new Date();
@Override
public void run() {
ExceptionUtils.doActionLogE(this::doRun);
}
private void doRun() throws Throwable {
// omitted for brevity – fetch mappers, iterate tasks, check validity, handle misfires, submit to executor
}
}Misfire Handling
If the current time is past the user‑defined end time, the task is disabled.
If the task has not yet reached its start time, execution is skipped.
On the first execution error, the task fires immediately and then follows the Cron schedule (similar to Quartz’s withMisfireHandlingInstructionFireAndProceed).
If there are missed executions, the scheduler runs them sequentially before resuming the normal schedule (similar to withMisfireHandlingInstructionIgnoreMisfires).
Task Execution
Execution is delegated to a TaskWork implementation. Before and after the business logic, common handling (locking, record persistence, error logging) is performed.
public class TaskWorkUtils {
static void helpRun(TaskWork localWork, ScheduleTask scheduleTask) {
// pseudo‑code for lock acquisition, record creation, execution, and post‑processing
}
}Conclusion
When the application starts, it initializes two scheduled threads: one for loading task definitions from the database into a cache, and another for evaluating those definitions and dispatching executable tasks to a worker pool. The design uses two tables (task definition and execution record) and two thread pools to achieve a flexible, user‑customizable scheduling solution.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
NetEase Smart Enterprise Tech+
Get cutting-edge insights from NetEase's CTO, access the most valuable tech knowledge, and learn NetEase's latest best practices. NetEase Smart Enterprise Tech+ helps you grow from a thinker into a tech expert.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
