本文介绍了是否可以手动调用Spring Scheduled方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法可以通过用户交互来调用Spring Scheduled方法(作业)?我需要创建一个显示所有作业的表,并且用户应该能够手动执行它们。确保作业可以自动运行,但用户应该可以手动启动它们。
Is there a way to call a spring scheduled method (job) through a user interaction? I need to create a table with shown all jobs and the user should be able to execute them manually. For sure the jobs run automatically but the user should be able to start them manually.
@Configuration
@EnableScheduling
public class ScheduleConfiguration {
@Bean
public ScheduledLockConfiguration taskScheduler(LockProvider
lockProvider) {
return ScheduledLockConfigurationBuilder
.withLockProvider(lockProvider)
.withPoolSize(15)
.withDefaultLockAtMostFor(Duration.ofHours(3))
.build();
}
@Bean
public LockProvider lockProvider(DataSource dataSource) {
return new JdbcTemplateLockProvider(dataSource);
}
}
@Component
public class MyService {
@Scheduled(fixedRateString = "1000")
@SchedulerLock(name = "MyService.process", lockAtLeastFor = 30000)
@Transactional
public void process() {
// do something
}
}
推荐答案
下面是使用 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:
Creating TaskScheduler
bean:
@Configuration
public class TaskSchedulerConfig {
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(5);
threadPoolTaskScheduler.setThreadNamePrefix("ThreadPoolTaskScheduler");
return threadPoolTaskScheduler;
}
}
定期执行的计划任务:
Scheduling task for periodic execution:
@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请求手动调用任务:
Manually invoking a task via a http request:
@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
}
}
这篇关于是否可以手动调用Spring Scheduled方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!