Dynamic Task scheduling with Spring Boot

public class SchedulingappApplication {

public static void main(String[] args) {
SpringApplication.run(SchedulingappApplication.class, args);

public class TaskDefinitionBean implements Runnable {

private TaskDefinition taskDefinition;

public void run() {
System.out.println("Running action: " + taskDefinition.getActionType());
System.out.println("With Data: " + taskDefinition.getData());

public TaskDefinition getTaskDefinition() {
return taskDefinition;

public void setTaskDefinition(TaskDefinition taskDefinition) {
this.taskDefinition = taskDefinition;
  • Sending an email
  • Sending a reminder notification
  • Reading data from a database and sending it elsewhere
public class TaskDefinition {

private String cronExpression;
private String actionType;
private String data;
public class TaskSchedulingService {

private TaskScheduler taskScheduler;

Map<String, ScheduledFuture<?>> jobsMap = new HashMap<>();

public void scheduleATask(String jobId, Runnable tasklet, String cronExpression) {
System.out.println("Scheduling task with job id: " + jobId + " and cron expression: " + cronExpression);
ScheduledFuture<?> scheduledTask = taskScheduler.schedule(tasklet, new CronTrigger(cronExpression, TimeZone.getTimeZone(TimeZone.getDefault().getID())));
jobsMap.put(jobId, scheduledTask);

public void removeScheduledTask(String jobId) {
ScheduledFuture<?> scheduledTask = jobsMap.get(jobId);
if(scheduledTask != null) {
jobsMap.put(jobId, null);
@RequestMapping(path = "/schedule")
public class JobSchedulingController {

private TaskSchedulingService taskSchedulingService;

private TaskDefinitionBean taskDefinitionBean;

@PostMapping(path="/taskdef", consumes = "application/json", produces="application/json")
public void scheduleATask(@RequestBody TaskDefinition taskDefinition) {
taskSchedulingService.scheduleATask(UuidGenerator.generateUuid(), taskDefinitionBean, taskDefinition.getCronExpression());

public void removeJob(@PathVariable String jobid) {
Postman Post request for task definition submission




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Setting proper server permissions

How to update a forked repo from original repo

Using auto keyword whenever possible in C++11

Snowflake Views in SqlDBM

Week 10 — BlackJack Sprint 1

Straightforward & Simple: Client-side Tracking

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ritesh Shergill

Ritesh Shergill

More from Medium

Token Bucket Rate limiter using Spring Boot and Redis, bucket4j

How to Check the Health of a Spring boot Application using Spring Actuator

Validating MongoDB Documents in Spring Boot

A MongoDB collection with a basic JSON schema

Key Differences Between Spring Boot and Spring Framework