Search code examples
springspring-mvcquartz-scheduler

Spring Quatrz Dynamic Annotation Based Java Config


Sorry i had to ask it over here as i searched a lot tried many things but failed to achieve the result.

So what i am trying to do is i have a service which give me the list of the Jobs along with the interval at which they need to run so , what i want to do is loop over the list of the jobs and schedule them using Spring Quartz and i want to do them using the java config and not XML based .

This application will be a web application which will be running on a server, a maven project.

I found result and the are mainly using the Custom Annotation . Is there any sample or example which i can try or use.?

The problem is we are very new to all this and none of us have a idea how to proceed with this so any help is very appreciated.

Thanks in advance, Vishesh


Solution

  • Have your @Confugation class implement SchedulingConfigurer. This allows you to schedule tasks programmatically. For example

        @Configuration
        @EnableScheduling
        public class TaskConfiguration implements SchedulingConfigurer{
    
            @Autowired
            private TaskDao taskDao; // implement TaskDao to read tasks from DB
    
           @Override
           public void configureTasks(ScheduledTaskRegistrar taskRegistrar){
               List<Task> tasks = taskDao.findAllTasks();
               for(Task task : tasks){
                   Runnable taskJob = createTaskJob(task); // create task by reflection
                  taskRegistrar.addCronTask(taskJob , task.getCronExpression());
               }
           }
        }
    
        public class Task implements Serializable{
    
             private String cronExpression;
             private String jobClass;
    
             //getters and setters
        }