问题描述
我设法使一个简单的应用程序在spring应用程序上下文中运行,并设法通过@Scheduled使它按计划运行:
@Scheduled(cron =“ 0 30 9 * * *,zone =” Australia / Sydney“)
有没有办法让@Scheduled在启动时运行?
我想到的是在application.properties中进行切换,例如:
scheduler.triggerNow = true
如果将其设置为true,则该应用将忽略spring cron计划并立即运行(在启动时运行一次),如果设置为false,则它将使用上面的spring cron计划并每天上午9:30运行
-
我去了https://start.spring.io,以获取一个可以使用的基本应用程序(maven项目,java,spring boot 2.3.4)
-
我看了一个YouTube视频来帮助设置调度程序:
我在主要班级有
@SpringBootApplication
@EnableConfigurationProperties
公共课程演示{
public static void main(String[] args){ ConfigurationApplicationContext ctx = new SpringApplicationBuilder(Demo.class) .web(WebApplicationType.None) .run(args) }
}
在新课程中,我添加了:
@配置
@EnableScheduling @ConditionalOnProperty(name =“ scheduling.enabled”,matchIfMissing = true)
public class Jobsched{ @Scheduled(cron="0 30 9 * * *",zone="Australia/Sydney") public void test(){ System.out.println("hello"); }
}
cron调度程序可以独立工作。而且我有一个可以禁用它的属性。我只想在启动时运行一次就禁用它(当前禁用它意味着它什么也不做)
这是一个非生产应用程序。计划在运行调度程序的情况下进行部署。而且,如果我想在本地运行它,只需禁用调度程序,使其在启动时运行
解决方法
在类组件(或服务...)中使用@PostConstruct
在启动时执行代码,
下面的示例显示了如何进行:
@Component
public class MyClass {
@PostConstruct
private void methodToExecute() {
doScheduledWOrk(); // call here for startup execution
}
@Scheduled(cron= "0 30 9 * * *,zone="Australia/Sydney")
public void scheduleMethod() {
doScheduledWOrk(); // sample function
}
public void doScheduledWOrk() {
//doing some scheduled stuff here...
}
}