Вот пример использования TaskScheduler
:
Создание задачи, которая будет запланирована и запущена вручную:
@Component
public class SomeTask implements Runnable {
private static final Logger log = LoggerFactory.getLogger();
@Autowired
public SomeDAO someDao;
@Override
public void run() {
// do stuff
}
}
Создание TaskScheduler
bean:
@Configuration
public class TaskSchedulerConfig {
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(5);
threadPoolTaskScheduler.setThreadNamePrefix("ThreadPoolTaskScheduler");
return threadPoolTaskScheduler;
}
}
Планирование задачи для периодического выполнения:
@Component
public class ScheduledTasks {
@Autowired private TaskScheduler taskScheduler;
// Tasks
@Autowired private SomeTask task1; // autowired in case the task has own autowired dependencies
@Autowired private AnotherTask task2;
@PostConstruct
public void scheduleTasks() {
taskScheduler.schedule(task1, new PeriodicTrigger(20, TimeUnit.SECONDS));
taskScheduler.schedule(task2, new CronTrigger("0 0 4 1/1 * ? *"));
}
}
Вызов задачи вручную через запрос http:
@Controller
public class TaskController {
@Autowired private TaskScheduler taskScheduler;
// Tasks
@Autowired private SomeTask task1;
@RequestMapping(value = "/executeTask")
public void executeTask() {
taskScheduler.schedule(task1, new Date()); // schedule task for current time
}
}