Eric
Eric

Reputation: 515

Allow the end user to schedule task with Spring Boot

I'm using Spring Boot and I want to allow the end user to schedule task as he wants.

I have a Spring Boot REST backend with a Angular frontend. The user should be able to schedule (with a crontab style syntax) a task (i.e. a class' method backend side), and choose some arguments.

The user should alse be able to view, edit, delete scheduled task from the front end

I know I can use @Scheduled annotation, but I don't see how the end user can schedule task with it. I also take a look at Quartz, but I don't see how to set the user's argument in my method call.

Should I use Spring Batch?

Upvotes: 3

Views: 2648

Answers (1)

shizhz
shizhz

Reputation: 12491

To schedule job programatically, you have the following options:

  • For simple cases you can have a look at ScheduledExecutorService, which can schedule commands to run after a given delay, or to execute periodically. It's in package java.util.concurrent and easy to use.
  • To schedule Crontab job dynamically, you can use quartz and here's official examples, basically what you'll do is:

    • Create instance Scheduler, which can be defined as a java bean and autowire by Spring, example code:
    • Create JobDetail
    • Create CronTrigger
    • Schedule the job with cron

Official example code(scheduled to run every 20 seconds):

SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();

JobDetail job = newJob(SimpleJob.class)
.withIdentity("job1", "group1")
.build();

CronTrigger trigger = newTrigger()
.withIdentity("trigger1", "group1")
.withSchedule(cronSchedule("0/20 * * * * ?"))
.build();

sched.scheduleJob(job, trigger);

Upvotes: 1

Related Questions