从外部JAR文件获取Spring Boot定时任务的cron表达式。

huangapple go评论75阅读模式
英文:

Get the spring boot scheduled cron expression from outside jar file

问题

以下是翻译的内容:

我有一个Spring Boot Java服务,我需要在特定的时间安排其运行。我已经启用了 @Enablescheduling@Scheduled 注解,并提供了cron表达式。

它正常运行。调度程序在预期的时间运行。但我关心的是,我应该从我的jar文件之外的某个地方控制cron表达式。我尝试将其用于属性文件,但在打包时,我的属性文件也被包含在其中。

示例代码:

@PostMapping(path = "getoktatodynamodb")
@Scheduled(cron = "0 0/5 0 * * ?")
@ApiOperation("同步数据到DynamoDB")
public FinalResponse getdatatodynamodb() {
    FinalResponse finalResponse = new FinalResponse();
    try {
        LOGGER.info("Sync data to DynamoDB starts - " + new Date());
        finalResponse = dynamodbuserService.dynamoDbSync();
    } catch (MyRestTemplateException ex) {
        LOGGER.error(ex.getMessage());
        finalResponse.setResponseMessage(ex.getMessage());
        finalResponse.setStatusCode(ex.getStatusCode().value());
    } catch (Exception execption) {
        LOGGER.error(execption.getMessage());
        finalResponse.setResponseMessage(execption.getMessage());
        finalResponse.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
    } finally {
        LOGGER.info("Sync data DynamoDB Ends - " + new Date());
    }
    return finalResponse;
}

主要意图是,调度程序应该在我们的控制之下,每当我们需要更改时间时,它应该是可配置的。无需更改代码并重新启动调度程序即可进行轻微更改。

我们应该如何实现这一点,还希望在Linux EC2实例中安排此任务?如果有更好的建议来实现这一点,请分享。

英文:

I have a spring boot java service I have to schedule to run on a particular time. I have enabled the @Enablescheduling and @Scheduled annotation and given the cron expression.

It's working fine. The scheduler is running at the expected time. But my concern is I should control the cron expression somewhere from outside my jar file. I have tried using it in property file but when packaging my property file also getting included in that.

Sample code:

    @PostMapping(path = "getoktatodynamodb")
	@Scheduled(cron = "0 0/5 0 * * ?")
	@ApiOperation("Sync data to DynamoDB")
	public FinalResponse getdatatodynamodb() {
		FinalResponse finalResponse = new FinalResponse();
		try {
			LOGGER.info("Sync data to DynamoDB starts - " + new Date());
			finalResponse = dynamodbuserService.dynamoDbSync();
		} catch (MyRestTemplateException ex) {
			LOGGER.error(ex.getMessage());
			finalResponse.setResponseMessage(ex.getMessage());
			finalResponse.setStatusCode(ex.getStatusCode().value());
		} catch (Exception execption) {
			LOGGER.error(execption.getMessage());
			finalResponse.setResponseMessage(execption.getMessage());
			finalResponse.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
		} finally {
			LOGGER.info("Sync data DynamoDB Ends - " + new Date());
		}
		return finalResponse;
	}

The main intention is scheduler should be in our control whenever we need to change the time it should be configurable. No code change and restarting the scheduler for minor changes.

How should we achieve this also we would like to schedule this in linux ec2 instance? in case if we have better suggestion to achieve this kindly share it.

答案1

得分: 2

以下是您要求的翻译内容:

你可以实现SchedulingConfigurer:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/SchedulingConfigurer.html

这篇DZone文章展示了一个非常好的例子:https://dzone.com/articles/schedulers-in-java-and-spring,我在这里展示,以防这篇文章不再保留。

@Configuration
@EnableScheduling
public class ScheduledConfiguration implements SchedulingConfigurer {
    TaskScheduler taskScheduler;
    private ScheduledFuture<?> job1;
    private ScheduledFuture<?> job2;
    
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.setPoolSize(10); // 设置线程池大小
        threadPoolTaskScheduler.setThreadNamePrefix("scheduler-thread");
        threadPoolTaskScheduler.initialize();
        job1(threadPoolTaskScheduler); // 将job1分配给调度程序
        // 将job1分配给调度程序
        this.taskScheduler = threadPoolTaskScheduler; // 在文章的后部分动态刷新cron表达式时将使用此对象
        taskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
    }
    
    private void job1(TaskScheduler scheduler) {
        job1 = scheduler.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " The Task1 executed at " + new Date());
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                String cronExp = "0/5 * * * * ?"; // 可以从数据库中获取
                return new CronTrigger(cronExp).nextExecutionTime(triggerContext);
            }
        });
    }
    
    private void job2(TaskScheduler scheduler) {
        job2 = scheduler.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " The Task2 executed at " + new Date());
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                String cronExp = "0/1 * * * * ?"; // 可以从数据库中获取,这将每分钟运行
                return new CronTrigger(cronExp).nextExecutionTime(triggerContext);
            }
        });
    }
}
英文:

You can implement SchedulingConfigurer:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/SchedulingConfigurer.html

This DZone article shows a really good example: https://dzone.com/articles/schedulers-in-java-and-spring which I'm showing here in case the article doesn't stay permanent.

@Configuration
@EnableScheduling
public class ScheduledConfiguration implements SchedulingConfigurer {
TaskScheduler taskScheduler;
private ScheduledFuture&lt;?&gt; job1;
private ScheduledFuture&lt;?&gt; job2;
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
ThreadPoolTaskScheduler threadPoolTaskScheduler =new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(10);// Set the pool of threads
threadPoolTaskScheduler.setThreadNamePrefix(&quot;scheduler-thread&quot;);
threadPoolTaskScheduler.initialize();
job1(threadPoolTaskScheduler);// Assign the job1 to the scheduler
// Assign the job1 to the scheduler
this.taskScheduler=threadPoolTaskScheduler;// this will be used in later part of the article during refreshing the cron expression dynamically
taskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
}
private void job1(TaskScheduler scheduler) {
job1 = scheduler.schedule(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + &quot; The Task1 executed at &quot; + new Date());
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
String cronExp = &quot;0/5 * * * * ?&quot;;// Can be pulled from a db .
return new CronTrigger(cronExp).nextExecutionTime(triggerContext);
}
});
}
private void job2(TaskScheduler scheduler){
job2=scheduler.schedule(new Runnable(){
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+&quot; The Task2 executed at &quot;+ new Date());
}
}, new Trigger(){
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
String cronExp=&quot;0/1 * * * * ?&quot;;//Can be pulled from a db . This will run every minute
return new CronTrigger(cronExp).nextExecutionTime(triggerContext);
}
});
}
}

huangapple
  • 本文由 发表于 2020年9月25日 11:53:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/64057568.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定