首页 文章

有没有办法在spring boot中的main方法中调用@Scheduled注释

提问于
浏览
1

我只是想通过使用@scheduler注释定期运行我的spring boot main方法 . 我已经指定了一些额外的代码,它们在启用REST服务之前会执行一些预先操作 .

@EnableScheduling
@SpringBootApplication
public class SpringBootJDBCApp {

    @Autowired
    ITest testService;

    public static void main(String args[]) throws Exception  {
        PersistenceValidation.cloneGit();
        PersistenceValidation.dataPersistance();
        PersistenceValidation.cleanUp();
        ApplicationContext context = SpringApplication
                .run(SpringBootJDBCApp.class);
        ITest testService = context.getBean(ITestService.class);
        testService.getAllData();
    }
}

我想每隔10秒运行一次上面的main方法 . 并在main方法中添加了@Schedule注释 . 但它引发了一个例外:

根据doc @Scheduler的预期行为应该被称为没有args []的方法

我想在main方法中使用 @Scheduler 注释如下:

@Scheduled(initialDelay = 1000, fixedRate = 10000)
public static void main(String args[]) throws Exception {
    PersistenceValidation.cloneGit();
    PersistenceValidation.dataPersistance();
    PersistenceValidation.cleanUp();
    ApplicationContext context = SpringApplication.run(SpringBootJDBCApp.class);
    ITest testService = context.getBean(ITestService.class);
    testService.getAllData();
}

Error

org.springframework.beans.factory.BeanCreationException:创建名为'springBootJDBCApp'的bean时出错:bean的初始化失败;嵌套异常是java.lang.IllegalStateException:遇到无效的@Scheduled方法'main':只有no-arg方法可以用@Scheduled注释

有没有其他方法可以完成这项任务?我想定期运行main方法中提到的所有内容 .

任何线索?

1 回答

  • 2

    使用@Scheduled注释注释的调度方法必须没有参数,因为注释不提供任何输入 . @Scheduled sais的Spring-docs:

    带注释的方法必须没有参数 . 它通常具有void返回类型;如果不是,则通过调度程序调用时将忽略返回的值 .

    您注释了以数组作为参数的方法 public static void main(String args[]) . 您必须将 main(String args[]) 中的内容包装成另一种方法 . 请注意,根本不使用 args[] .

相关问题