gpt4 book ai didi

java - 如何在多个时间间隔安排作业运行

转载 作者:行者123 更新时间:2023-11-29 03:08:37 26 4
gpt4 key购买 nike

我们有一个简单的要求,即从不同的端点服务器下载文件。我们将安排这些文件下载在一天中的不同时间进行(可从 GUI 自定义)。我们一直在使用 Spring Scheduling 及其用于从单个服务器下载单个作业的工作。

现在我们想将这种下载文件的操作扩展到多个服务器和不同的时间。文件下载的操作是相同的,但它运行的时间、端点服务器、下载所有内容的位置都会因任务而异。基本上我们将对这些属性进行参数化并希望重复使用相同的作业来下载文件。这可能吗?

如何使用 Spring Scheduling 实现这一点?

最佳答案

The schedule(TimerTask task,long delay,long period) method is used to schedule the specified task for repeated fixed-delay execution, beginning after the specified delay.

public class TimerClassExample {
public static void scheduleTaskOfDownload(Date SchedulerStartTime,Long SchedulerInterval) {
// creating timer task, timer
TimerTask tasknew = new MyFileDownloader (serverName);
Timer timer = new Timer();

// scheduling the task at interval
timer.schedule(tasknew,SchedulerStartTime, SchedulerInterval);
}

}

您可以有一个如下所示的 timerTask,您可以从中调用下载逻辑:-

public class MyFileDownloader extends TimerTask {
String serverName;
MyFileDownloader(String serverName){this.serverName= serverName}
@Override
public void run() {
System.out.println("Timer task started at:"+new Date());
downloadFiles(serverName);//your code which downloads file from server
System.out.println("Timer task finished at:"+new Date());
}
}

现在,当您的应用程序启动时,您可以使用此代码调用我们的调度程序方法 scheduleTaskOfDownload

@Component
public class StartupHousekeeper implements ApplicationListener<ContextRefreshedEvent> {

@Override
public void onApplicationEvent(final ContextRefreshedEvent event) {

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 5);
cal.set(Calendar.MINUTE, 30);
//I am passing same time in both calls but you can pass different dates
TimerClassExample.scheduleTaskOfDownload(cal.getTime(),TimeUnit.MILLISECONDS.convert(3, TimeUnit.HOURS));
TimerClassExample.scheduleTaskOfDownload(cal.getTime(),TimeUnit.MILLISECONDS.convert(2, TimeUnit.HOURS));

//also keeping interval as 2 and 3 hours respectively but you choose different interval like 24 hrs in that place
}
}

关于java - 如何在多个时间间隔安排作业运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30725066/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com