每次在特定时间段后都需要使用 java 运行特定方法



我需要自动化我的API案例,其中我用来运行API的令牌每一小时就会过期。所以我需要使用特定方法重新生成令牌。当我运行自动化时,如何在每小时后运行此特定方法?

你可以简单地使用EnableScheduleing

像这样的东西应该可以解决问题(改编自Javadoc for @EnableScheduling):

@Configuration
@EnableScheduling
public class MyAppConfig implements SchedulingConfigurer {
    @Autowired
    Environment env;
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
    @Bean(destroyMethod = "shutdown")
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(100);
    }
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
        taskRegistrar.addTriggerTask(
                new Runnable() {
                    @Override public void run() {
                        myBean().getSchedule();
                    }
                },
                new Trigger() {
                    @Override public Date nextExecutionTime(TriggerContext triggerContext) {
                        Calendar nextExecutionTime =  new GregorianCalendar();
                        Date lastActualExecutionTime = triggerContext.lastActualExecutionTime();
                        nextExecutionTime.setTime(lastActualExecutionTime != null ? lastActualExecutionTime : new Date());
                        nextExecutionTime.add(Calendar.MILLISECOND, env.getProperty("myRate", Integer.class)); //you can get the value from wherever you want
                        return nextExecutionTime.getTime();
                    }
                }
        );
    }
}

另一种方法是将 @Scheduled(cron = "0 0 0/1 1/1 * ?") 放在您的 API 调用方法之前,如下所示:

@Scheduled(cron = "0 15 10 15 * ?")
public void scheduleTaskUsingCronExpression() {
    long now = System.currentTimeMillis() / 1000;
    System.out.println(
      "schedule tasks using cron jobs - " + now);
}

您可以尝试睡眠方法。

new Thread(()->{
    while(true) {
        method(); //your method
        Thread.sleep(3600000);
    }
}).start();

你可以使用类似cron的东西和方法"scheduleAtFixedRate"

如何创建 Java cron 作业

最新更新