每5分钟更新一次变量的值

时间:2013-10-22 12:49:17

标签: java multithreading parallel-processing

我有一个变量,其值需要每5分钟更新一次,具体取决于条件。我知道我需要开始一个不同的线程。但是我该怎么做呢?

5 个答案:

答案 0 :(得分:3)

使用ScheduledThreadPoolExecutor

public class Main{
 public static void main(String args[]) {
   ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(2);    
   stpe.scheduleAtFixedRate(new YourJob(), 0, 5, TimeUnit.MINUTES);
 }
}

class YourJob implements Runnable {
   public void run() {
   // your task
    System.out.println("Job 1");
  }
}

答案 1 :(得分:2)

使用Quartz Scheduler

这更容易..安排任务..

java在预定时间内运行程序是件好事

  • Quartz Schedular功能,推迟在给定时间运行的任务
  • 循环执行也可用

答案 2 :(得分:1)

线程方式,

Thread t= new Thread(new Runnable() 
    {           
        public void run() 
        {
            while(true)
            {
                try 
                {
                    Thread.sleep(5 * 60 * 1000);
                    //change your variable values as required                       
                } 
                catch (InterruptedException e) 
                {

                }                                   
            }
        }
    });

线程池执行方式,

public static void main(String args[]) 
    {
        ScheduledThreadPoolExecutor myPool = new ScheduledThreadPoolExecutor(2);    
        myPool.scheduleAtFixedRate(new MyJob(), 0, 5 , TimeUnit.MINUTES);       
    }
    class MyJob implements Runnable
    {
        public void run() 
        {
            //change your variable values as required in this function as this will be invoked every 5 minutes             
        }
    }

计时器实施

Timer timer =new Timer();
        TimerTask task = new TimerTask() 
        {

            @Override
            public void run() 
            {
                //change your variable values as required in this function as this will be invoked every 5 minutes   

            }
        };
        timer.schedule(task, new Date(), 5 * 60 * 1000); //Use this if you want the new task to be invoked after completion of prior task only              
        timer.scheduleAtFixedRate(task, new Date(), 5 * 60 * 1000);//Use this if you want the new task to be invoked after fixed interval 
                                                                   //but will no depend or wait on completion of the prior task 

答案 3 :(得分:0)

如何使用java.util.Timer

答案 4 :(得分:0)

如果您使用的是Spring,则可以使用@Scheduled注释您的方法,例如:

// Invoke method every 300000 ms (5 minutes)
@Scheduled(fixedDelay=300000)
public void myMethod() {
    // Your code here
}

或者您可以查看Spring的文档:http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#scheduling-annotation-support-scheduled