我们从不同的终端服务器下载文件的简单要求。我们将这些文件下载安排在当天的不同时间进行(可从GUI自定义)。我们一直在使用Spring Scheduling&它可以从单个服务器上下载单个作业。
现在我们希望将这些文件的下载操作扩展到多个服务器和不同的时间。文件下载的操作是相同的,但是它将运行的时间,终点服务器,下载所有内容的位置将根据任务而改变。基本上我们将参数化这些属性&想重用相同的工作来下载文件。这可能吗?
如何使用Spring Scheduling实现这一目标?
答案 0 :(得分:2)
我建议将spring与Quartz作业调度程序集成。在哪里可以决定:
- 使用在每个预定时间运行一次的单个cron作业。每次调用都会获取另一个spring bean或数据库表提供的参数
或
- 使用给定参数在预定时间创建单独的作业。
答案 1 :(得分:2)
调度(TimerTask任务,长延迟,长周期)方法用于在指定的延迟之后开始,为重复的固定延迟执行调度指定的任务。
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
}
}