<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jonathan de Paula on Medium]]></title>
        <description><![CDATA[Stories by Jonathan de Paula on Medium]]></description>
        <link>https://medium.com/@jonathanpaula22?source=rss-c6ac535036d1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yRLN_jguwGoaDrgECvWdNw.jpeg</url>
            <title>Stories by Jonathan de Paula on Medium</title>
            <link>https://medium.com/@jonathanpaula22?source=rss-c6ac535036d1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 12:12:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jonathanpaula22/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Dynamically scheduling recurring tasks in a Multi-Instance environment]]></title>
            <link>https://medium.com/wearewaes/dynamically-scheduling-recurring-tasks-in-a-multi-instance-environment-a9f83df85c7b?source=rss-c6ac535036d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9f83df85c7b</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[schedule]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Jonathan de Paula]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 12:49:16 GMT</pubDate>
            <atom:updated>2025-04-24T12:49:16.687Z</atom:updated>
            <content:encoded><![CDATA[<p>I faced a challenge in my team: how to dynamically schedule recurring tasks in a cloud-based, multi-instance environment so we could benefit from the cloud’s scalability and reliability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWjbDVULGK64GP0VAdT4kQ.jpeg" /></figure><p>Previously, we used an on-premises infrastructure where recurring tasks were scheduled using Spring’s TaskScheduler. This interface allows scheduling tasks with fixed-rate, fixed-delay, or cron-like expressions. You can read more about it <a href="https://docs.spring.io/spring-framework/reference/integration/scheduling.html#scheduling-task-scheduler">here</a>.</p><p>The tasks were dynamically generated in response to events, and each task executed at its own time based on a cron schedule. This setup worked perfectly in a single-instance, on-prem environment.</p><p>However, moving to the cloud introduced new challenges:</p><ul><li><strong>No duplicate task execution:</strong> Tasks must not run on multiple instances simultaneously.</li><li><strong>Failover support:</strong> If one instance shuts down, others should pick up its tasks.</li><li><strong>Recovery after downtime:</strong> If all instances go down, tasks should resume when the service recovers.</li><li><strong>Task management:</strong> Tasks should support updates, pauses, and deletions.</li></ul><p>Meeting these requirements in a cloud environment is no small feat.</p><h3>Presenting db-scheduler</h3><p>After some research, I discovered a library called <a href="https://github.com/kagkarlsson/db-scheduler">db-scheduler</a>. According to its documentation, it is a <em>task scheduler for Java inspired by the need for a clustered </em><em>java.util.concurrent.ScheduledExecutorService.</em></p><h4>Key Features</h4><ul><li><strong>Cluster-friendly:</strong> Guarantees execution by a single scheduler instance. (Nice!)</li><li><strong>Persistent tasks:</strong> Uses a single database table for persistence. (Wow!)</li><li><strong>Simple:</strong> Easy to use. (I’m in love.)</li><li><strong>And more!</strong> Check out the complete list of features <a href="https://github.com/kagkarlsson/db-scheduler?tab=readme-ov-file#features">here</a>.</li></ul><h4>What Can It Do?</h4><p>db-scheduler supports:</p><ul><li><strong>Recurring static tasks:</strong> For example, sending customers daily emails with recent transactions.</li><li><strong>One-time tasks:</strong> Useful for tasks that need to run at application startup.</li><li><strong>Batch tasks:</strong> Schedule multiple tasks at once.</li></ul><p>But how does it help with my specific problem?</p><h3>How <strong>db-scheduler</strong> Solved My Problem</h3><h4>Addressing the Challenges</h4><ol><li>No duplicate execution: db-scheduler ensures that tasks are executed by only one instance at a time.</li><li>Failover support: Tasks are persisted in a database, so new instances can pick up where others left off.</li><li>Recovery after downtime: The database acts as a single source of truth, enabling recovery after all instances go down.</li></ol><p>What remained was the ability to schedule, update, delete, and pause tasks dynamically.</p><h3>Implementation</h3><p>Let’s see now how I implemented it.</p><h4>Adding the Dependency</h4><p>First, I added the db-scheduler dependency to my project:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.github.kagkarlsson&lt;/groupId&gt;<br>    &lt;artifactId&gt;db-scheduler-spring-boot-starter&lt;/artifactId&gt;<br>    &lt;version&gt;15.1.1&lt;/version&gt;<br>&lt;/dependency&gt;</pre><h4>Database Setup</h4><p>I used the script in the <a href="https://github.com/kagkarlsson/db-scheduler/blob/master/db-scheduler/src/test/resources/postgresql_tables.sql">documentation</a> to create the necessary database table.</p><h4>Scheduler Bean</h4><p>The Scheduler bean is the core of the setup. It handles task scheduling and execution.</p><pre>public static final String DYNAMIC_RECURRING_TASK_NAME = &quot;dynamic-recurring-task&quot;;<br>public static final TaskDescriptor&lt;ScheduleAndNoData&gt; DYNAMIC_RECURRING_TASK =<br>        TaskDescriptor.of(DYNAMIC_RECURRING_TASK_NAME, ScheduleAndNoData.class);<br><br>@Bean<br>public Scheduler scheduler(DataSource dataSource, TaskExecutorService taskExecutorService, ScheduledTaskRepository scheduledTaskRepository) {<br>    final RecurringTaskWithPersistentSchedule&lt;ScheduleAndNoData&gt; dynamicRecurringTask =<br>            Tasks.recurringWithPersistentSchedule(DYNAMIC_RECURRING_TASK)<br>                    .execute((taskInstance, executionContext) -&gt; taskExecutorService.startTaskExecution(taskInstance.getId()));<br><br>    Scheduler scheduler = Scheduler.create(dataSource, dynamicRecurringTask)<br>            .pollingInterval(Duration.ofSeconds(1))<br>            .addExecutionInterceptor(new TaskExecutionCustomInterceptor(scheduledTaskRepository))<br>            .registerShutdownHook()<br>            .build();<br><br>    scheduler.start();<br><br>    return scheduler;<br>}</pre><h4>Task Descriptor</h4><p>The TaskDescriptor defines the characteristics of a task, such as its name and associated data type.</p><pre>public static final String DYNAMIC_RECURRING_TASK_NAME = &quot;dynamic-recurring-task&quot;;<br>public static final TaskDescriptor&lt;ScheduleAndNoData&gt; DYNAMIC_RECURRING_TASK =<br>        TaskDescriptor.of(DYNAMIC_RECURRING_TASK_NAME, ScheduleAndNoData.class);</pre><h4>Data Object</h4><p>The ScheduleAndNoData class implements the ScheduleAndData interface. It includes the task&#39;s schedule and the isOnHold flag to determine whether the task should execute.</p><pre>@Getter<br>@RequiredArgsConstructor<br>public static class ScheduleAndNoData implements ScheduleAndData, Serializable {<br>    @Serial<br>    private static final long serialVersionUID = 1L;<br>    private final CronSchedule schedule;<br>    private final boolean isOnHold;<br><br>    @Override<br>    public Object getData() {<br>        return null;<br>    }<br>}</pre><h4>Execution Interceptor</h4><p>The TaskExecutionCustomInterceptor intercepts task execution to handle tasks that are on hold.</p><p>The ExecutionInterceptor is an interface that, when implemented, allows you to intercept task execution and modify the task&#39;s state, data, schedule or even cancel it. Here, I used different types of CompletitionHandler that the library offers.</p><p>In summary, you can use OnCompleteReschedule for recurring tasks that are on hold, so they are not executed at this time. Use OnCompleteReplace when you need to update the task&#39;s state or schedule.</p><pre>@RequiredArgsConstructor<br>@Slf4j<br>static class TaskExecutionCustomInterceptor implements ExecutionInterceptor {<br>    private final ScheduledTaskRepository scheduledTaskRepository;<br><br>    private static boolean isDynamicRecurringTask(TaskInstance&lt;?&gt; taskInstance) {<br>        return taskInstance.getTaskName().equals(DYNAMIC_RECURRING_TASK_NAME) &amp;&amp;<br>                taskInstance.getData() instanceof ScheduleAndNoData;<br>    }<br><br>    @Override<br>    public CompletionHandler&lt;?&gt; execute(TaskInstance&lt;?&gt; taskInstance, ExecutionContext executionContext, ExecutionChain executionChain) {<br>        log.info(&quot;Custom interceptor is being executed&quot;);<br>        if (isDynamicRecurringTask(taskInstance)) {<br>            TaskInstance&lt;ScheduleAndNoData&gt; taskInstanceWithSchedule = (TaskInstance&lt;ScheduleAndNoData&gt;) taskInstance;<br>            if (isOnHold(taskInstanceWithSchedule)) {<br>                return handleOnHold(taskInstanceWithSchedule);<br>            }<br>            if (!isOnHold(taskInstanceWithSchedule) &amp;&amp; isOnHoldDb(taskInstanceWithSchedule)) {<br>                return handleOnHoldNotInSyncWithDb(&quot;Task is on hold on the DB. Will be replaced&quot;, true, taskInstanceWithSchedule);<br>            }<br>        }<br>        log.info(&quot;Proceeding with the task execution&quot;);<br>        return executionChain.proceed(taskInstance, executionContext);<br>    }<br><br>    private CompletionHandler.OnCompleteReplace&lt;ScheduleAndNoData&gt; handleOnHoldNotInSyncWithDb(String log, boolean isOnHold, TaskInstance&lt;ScheduleAndNoData&gt; taskInstanceWithSchedule) {<br>        TaskExecutionCustomInterceptor.log.info(log);<br>        ScheduleAndNoData newData = new ScheduleAndNoData(taskInstanceWithSchedule.getData().getSchedule(), isOnHold);<br>        return new CompletionHandler.OnCompleteReplace&lt;&gt;(taskInstanceWithSchedule.getTaskName(), newData);<br>    }<br><br>    private CompletionHandler&lt;?&gt; handleOnHold(TaskInstance&lt;ScheduleAndNoData&gt; taskInstanceWithSchedule) {<br>        if (isOnHoldDb(taskInstanceWithSchedule)) {<br>            return rescheduleTaskExecutor(taskInstanceWithSchedule);<br>        }<br>        return handleOnHoldNotInSyncWithDb(&quot;Task was on hold. Will be replaced&quot;, false, taskInstanceWithSchedule);<br>    }<br><br>    private CompletionHandler.OnCompleteReschedule&lt;Object&gt; rescheduleTaskExecutor(TaskInstance&lt;ScheduleAndNoData&gt; taskInstanceWithSchedule) {<br>        log.info(&quot;Task is on hold. Will be rescheduled&quot;);<br>        return new CompletionHandler.OnCompleteReschedule&lt;&gt;(taskInstanceWithSchedule.getData().getSchedule());<br>    }<br><br>    private boolean isOnHold(TaskInstance&lt;ScheduleAndNoData&gt; taskInstanceWithSchedule) {<br>        return taskInstanceWithSchedule.getData().isOnHold();<br>    }<br><br>    private boolean isOnHoldDb(TaskInstance&lt;ScheduleAndNoData&gt; taskInstanceWithSchedule) {<br>        return scheduledTaskRepository.findByIdAndOnHoldTrue(taskInstanceWithSchedule.getId()).isPresent();<br>    }<br>}</pre><h3>Dynamic Task Scheduling</h3><p>The TaskSchedulerService handles dynamic scheduling, updating, and cancelling of tasks.</p><pre>@Service<br>@Slf4j<br>@RequiredArgsConstructor<br>public class TaskSchedulerService {<br>    private final Scheduler scheduler;<br><br>    public void scheduleTaskExecution(String taskId, String trigger) {<br>        log.info(&quot;Schedule task with taskId: {}&quot;, taskId);<br>        this.scheduler.scheduleIfNotExists(DYNAMIC_RECURRING_TASK<br>                .instance(taskId)<br>                .data(new SchedulerConfiguration.ScheduleAndNoData(new CronSchedule(trigger), false))<br>                .scheduledAccordingToData());<br>    }<br><br>    public void cancelTaskExecution(String taskId) {<br>        log.info(&quot;Cancel task with taskId: {}&quot;, taskId);<br>        try {<br>            this.scheduler.cancel(new TaskInstance&lt;&gt;(DYNAMIC_RECURRING_TASK_NAME, taskId));<br>        } catch (TaskInstanceNotFoundException e) {<br>            log.warn(&quot;Task not found with taskId: {}&quot;, taskId);<br>        } catch (TaskInstanceCurrentlyExecutingException e) {<br>            log.warn(&quot;Task with taskId {} is currently executing. Will be cancelled after execution.&quot;, taskId);<br>        }<br>        // in both exceptions, you can choose how you handle according to the project needs.<br>        // let&#39;s assume that after this succeeds, the task data is deleted also on the repository<br>    }<br><br>    public void updateTaskExecution(String taskId, String trigger, boolean onHold) {<br>        log.info(&quot;Update task with taskId: {}&quot;, taskId);<br>        this.cancelTaskExecution(taskId);<br>        this.scheduler.scheduleIfNotExists(DYNAMIC_RECURRING_TASK<br>                .instance(taskId)<br>                .data(new SchedulerConfiguration.ScheduleAndNoData(new CronSchedule(trigger), onHold))<br>                .scheduledAccordingToData());<br>    }<br>}</pre><h3>Testing the service:</h3><p>I created a simple controller to schedule, cancel, and update tasks as a test:</p><ol><li>I created an integration test that spins up 2 instances and schedules 2 tasks that run every 5 seconds.</li><li>Then, I stop instance 1 and create instance 3.</li><li>Finally, I stop instance 2 and create instance 4.</li></ol><p>The test ensures that the tasks are not executed by more than one instance at a time and that they run every 5 seconds.</p><p>You can check the test <a href="https://github.com/JhonydePaula22/db-scheduler-example/blob/main/src/test/java/we/arewaes/dynamicallytaskscheduler/MultiInstanceDynamicallyTaskSchedulerITTest.java">here</a>.</p><h3>Conclusion</h3><p>Using db-scheduler, I successfully implemented dynamic task scheduling in a multi-instance environment. The solution ensures no duplicate execution, supports failover, and allows tasks to be updated, paused, or deleted.</p><p>You can find the complete code in this <a href="https://github.com/JhonydePaula22/db-scheduler-example">GitHub repository</a>.</p><h3>Do you think you have what it takes to be one of us?</h3><p>At <a href="https://wearewaes.com/">WAES</a>, we are always looking for the best developers and data engineers to help Dutch companies succeed. If you are interested in becoming a part of our team and moving to The Netherlands, look at our open positions <a href="https://wearewaes.com/jobs-overview/">here</a>.</p><h3>WAES publication</h3><p>Our content creators constantly create new articles about software development, lifestyle, and WAES. So make sure to follow us on Medium to learn more.</p><p>Also, make sure to follow us on our social media:<br><a href="https://www.linkedin.com/company/wearewaes/">LinkedIn</a> — <a href="https://www.instagram.com/wearewaes/">Instagram</a> — <a href="https://twitter.com/WEAREWAES">Twitter</a> — <a href="https://www.youtube.com/channel/UC92trFLzhhJ_g9xJZuWZXWA">YouTube</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9f83df85c7b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wearewaes/dynamically-scheduling-recurring-tasks-in-a-multi-instance-environment-a9f83df85c7b">Dynamically scheduling recurring tasks in a Multi-Instance environment</a> was originally published in <a href="https://medium.com/wearewaes">WAES</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>