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

Is there any way to call @Scheduled annotation in main method in spring boot

我只想 运行 我的 spring 通过使用 @scheduler 批注定期启动主方法。我已经指定了一些额外的代码,这些代码将在启用 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();
    }
}

我想运行上面的main方法每10秒执行一次。并在 main 方法中添加了 @Schedule 注解。但它抛出一个异常:

Expected behavior as per doc @Scheduler should be called a method which doesn't have 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();
}

错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springBootJDBCApp': Initialization of bean failed; nested exception is java.lang.IllegalStateException: Encountered invalid @Scheduled method 'main': Only no-arg methods may be annotated with @Scheduled

还有其他方法可以完成这个任务吗?我想要 运行 定期在主要方法中提到的全部内容。

有线索吗?

@Scheduled annotation must have no arguments because the annotation doesn't provide any input. The Spring-docs of @Scheduled注释的调度方法sais:

The annotated method must expect no arguments. It will typically have a void return type; if not, the returned value will be ignored when called through the scheduler.

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