我有一个变量,其值需要根据条件每 5 分钟更新一次。我知道我需要启动一个不同的线程。但我该怎么做呢?
问问题
2972 次
5 回答
3
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");
}
}
于 2013-10-22T12:55:03.833 回答
2
于 2013-10-22T12:54:00.393 回答
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
于 2013-10-22T13:02:57.443 回答
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-预定的
于 2013-10-22T13:14:31.203 回答
0
怎么用java.util.Timer
?
于 2013-10-22T12:51:55.970 回答