可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I need to schedule a task to run in at fixed interval of time. How can I do this with support of long intervals (for example on each 8 hours)?
I\'m currently using java.util.Timer.scheduleAtFixedRate
. Does java.util.Timer.scheduleAtFixedRate
support long time intervals?
回答1:
Use a ScheduledExecutorService:
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(yourRunnable, 8, 8, TimeUnit.HOURS);
回答2:
You should take a look to Quartz it\'s a java framework wich works with EE and SE editions and allows to define jobs to execute an specific time
回答3:
Try this way ->
Firstly create a class TimeTask that run your task, it looks like:
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());
}
}
}
then in main class you instantiate the task and run it periodically started by a specified date:
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));
}
回答4:
Use Google Guava AbstractScheduledService
as given below:
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();
}
}
If you have more services like this, then registering all services in ServiceManager will be good as all services can be started and stopped together. Read here for more on ServiceManager.
回答5:
If you want to stick with java.util.Timer
, you can use it to schedule at large time intervals. You simply pass in the period you are shooting for. Check the documentation here.
回答6:
If your application is already using Spring framework, you have Scheduling built in
回答7:
Do something every one second
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
//code
}
}, 0, 1000);
回答8:
I use Spring Framework\'s feature. (spring-context jar or maven dependency).
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();
}
}
ScheduledTask is my own interface with my custom method execute, which I call as my scheduled task.
回答9:
If you need a run the scheduled task in the thread mode.
Class ScheduledThreadPoolExecutor is recommended.
public class ScheduledThreadPoolExecutor
extends ThreadPoolExecutor
implements ScheduledExecutorService
A ThreadPoolExecutor that can additionally schedule commands to run
after a given delay, or to execute periodically. This class is
preferable to Timer when multiple worker threads are needed, or when
the additional flexibility or capabilities of ThreadPoolExecutor
(which this class extends) are required. Delayed tasks execute no
sooner than they are enabled, but without any real-time guarantees
about when, after they are enabled, they will commence. Tasks
scheduled for exactly the same execution time are enabled in
first-in-first-out (FIFO) order of submission.
When a submitted task is cancelled before it is run, execution is
suppressed. By default, such a cancelled task is not automatically
removed from the work queue until its delay elapses. While this
enables further inspection and monitoring, it may also cause unbounded
retention of cancelled tasks. To avoid this, use
setRemoveOnCancelPolicy(boolean) to cause tasks to be immediately
removed from the work queue at time of cancellation.
Successive executions of a periodic task scheduled via
scheduleAtFixedRate or scheduleWithFixedDelay do not overlap. While
different executions may be performed by different threads, the
effects of prior executions happen-before those of subsequent ones.
While this class inherits from ThreadPoolExecutor, a few of the
inherited tuning methods are not useful for it. In particular, because
it acts as a fixed-sized pool using corePoolSize threads and an
unbounded queue, adjustments to maximumPoolSize have no useful effect.
Additionally, it is almost never a good idea to set corePoolSize to
zero or use allowCoreThreadTimeOut because this may leave the pool
without threads to handle tasks once they become eligible to run.
回答10:
Here are a few ways to run schedule task periodically:
1. Scheduler Task
import java.util.TimerTask;
import java.util.Date;
public class ScheduledTask extends TimerTask { // Create a class extends with TimerTask
Date now;
public void run() { //Write your code in public void run() method that you want to execute periodically.
now = new Date(); // initialize date
System.out.println(\"Time is :\" + now); // Display current time
}
}
2. Run Scheduler Task
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 Repetitively task for every 1 secs
//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);
}
}
}
}
Reference https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/
回答11:
Have you tried Spring Scheduler using annotations ?
@Scheduled(cron = \"0 0 0/8 ? * * *\")
public void scheduledMethodNoReturnValue(){
//body can be another method call which returns some value.
}
you can do this with xml as well.
<task:scheduled-tasks>
<task:scheduled ref = \"reference\" method = \"methodName\" cron = \"<cron expression here> -or- ${<cron expression from property files>}\"
<task:scheduled-tasks>