gpt4 book ai didi

spring - 是否可以手动调用Spring Scheduled方法

转载 作者:行者123 更新时间:2023-12-01 03:13:51 31 4
gpt4 key购买 nike

有没有一种方法可以通过用户交互来调用spring调度的方法(作业)?我需要创建一个显示所有作业的表,并且用户应该能够手动执行它们。当然,作业会自动运行,但用户应该能够手动启动它们。

@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:
@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
}
}

关于spring - 是否可以手动调用Spring Scheduled方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50151816/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com