RYN*_*RYN 168 java scheduled-tasks
我需要安排一个任务以固定的时间间隔运行.如何在长时间间隔(例如每8小时)的支持下完成此操作?
我正在使用java.util.Timer.scheduleAtFixedRate.是否java.util.Timer.scheduleAtFixedRate支持长时间间隔?
b_e*_*erb 243
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(yourRunnable, 8, 8, TimeUnit.HOURS);
Run Code Online (Sandbox Code Playgroud)
She*_*uky 22
试试这种方式 - >
首先创建一个运行任务的类TimeTask,它看起来像:
public class CustomTask extends TimerTask {
public CustomTask(){
//Constructor
}
public void run() {
try {
// Your task process
} catch (Exception ex) {
System.out.println("error running thread " + ex.getMessage());
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在主类中实例化任务并在指定日期之前定期运行它:
public void runTask() {
Calendar calendar = Calendar.getInstance();
calendar.set(
Calendar.DAY_OF_WEEK,
Calendar.MONDAY
);
calendar.set(Calendar.HOUR_OF_DAY, 15);
calendar.set(Calendar.MINUTE, 40);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Timer time = new Timer(); // Instantiate Timer Object
// Start running the task on Monday at 15:40:00, period is set to 8 hours
// if you want to run the task immediately, set the 2nd parameter to 0
time.schedule(new CustomTask(), calendar.getTime(), TimeUnit.HOURS.toMillis(8));
}
Run Code Online (Sandbox Code Playgroud)
Ari*_*ali 13
使用Google Guava AbstractScheduledService,如下所示:
public class ScheduledExecutor extends AbstractScheduledService
{
@Override
protected void runOneIteration() throws Exception
{
System.out.println("Executing....");
}
@Override
protected Scheduler scheduler()
{
return Scheduler.newFixedRateSchedule(0, 3, TimeUnit.SECONDS);
}
@Override
protected void startUp()
{
System.out.println("StartUp Activity....");
}
@Override
protected void shutDown()
{
System.out.println("Shutdown Activity...");
}
public static void main(String[] args) throws InterruptedException
{
ScheduledExecutor se = new ScheduledExecutor();
se.startAsync();
Thread.sleep(15000);
se.stopAsync();
}
Run Code Online (Sandbox Code Playgroud)
}
如果你有更多这样的服务,那么在ServiceManager中注册所有服务都会很好,因为所有服务都可以一起启动和停止.有关ServiceManager的更多信息,请阅读此处
我使用 Spring Framework 的特性。(spring-context jar 或 maven 依赖项)。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTaskRunner {
@Autowired
@Qualifier("TempFilesCleanerExecution")
private ScheduledTask tempDataCleanerExecution;
@Scheduled(fixedDelay = TempFilesCleanerExecution.INTERVAL_TO_RUN_TMP_CLEAN_MS /* 1000 */)
public void performCleanTempData() {
tempDataCleanerExecution.execute();
}
}
Run Code Online (Sandbox Code Playgroud)
ScheduledTask是我自己的接口与我的自定义方法execute,我称之为我的计划任务。
小智 5
每一秒做一件事
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
//code
}
}, 0, 1000);
Run Code Online (Sandbox Code Playgroud)
小智 5
这两个类可以一起工作来安排一个周期性的任务:
import java.util.TimerTask;
import java.util.Date;
// Create a class extending TimerTask
public class ScheduledTask extends TimerTask {
Date now;
public void run() {
// Write code here that you want to execute periodically.
now = new Date(); // initialize date
System.out.println("Time is :" + now); // Display current time
}
}
Run Code Online (Sandbox Code Playgroud)
import java.util.Timer;
public class SchedulerMain {
public static void main(String args[]) throws InterruptedException {
Timer time = new Timer(); // Instantiate Timer Object
ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
time.schedule(st, 0, 1000); // Create task repeating every 1 sec
//for demo only.
for (int i = 0; i <= 5; i++) {
System.out.println("Execution in Main Thread...." + i);
Thread.sleep(2000);
if (i == 5) {
System.out.println("Application Terminates");
System.exit(0);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
参考https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/
小智 5
您还可以使用JobRunr,这是一个易于使用的开源 Java Scheduler。
要使用 JobRunr 每 8 小时安排一次作业,您可以使用以下代码:
BackgroundJob.scheduleRecurrently(Duration.ofHours(8), () -> yourService.methodToRunEvery8Hours());
Run Code Online (Sandbox Code Playgroud)
如果您使用的是 Spring Boot、Micronaut 或 Quarkus,还可以使用该@Recurring注解:
public class YourService {
@Recurring(interval="PT8H")
public void methodToRunEvery8Hours() {
// your business logic
}
}
Run Code Online (Sandbox Code Playgroud)
JobRunr 还配备了嵌入式仪表板,可让您跟踪工作的进展情况。
| 归档时间: |
|
| 查看次数: |
242654 次 |
| 最近记录: |