Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何启动一个定时但有固定时间的计时器_Java_Timer_Future_Timertask - Fatal编程技术网

Java 如何启动一个定时但有固定时间的计时器

Java 如何启动一个定时但有固定时间的计时器,java,timer,future,timertask,Java,Timer,Future,Timertask,我正在开发一个系统,它必须每隔N秒定期启动一个任务(下载一个文件)。这不是一个问题,我使用Timer和Timertask进行了如下操作: FileTimer rXMLFileTimer; private static Timer timer = new Timer("FileReader"); rXMLFileTimer = new ReadFileTimer(); int myDelay = 30; timer.scheduleAtFixedRate(rXMLFileTimer, 0, my

我正在开发一个系统,它必须每隔N秒定期启动一个任务(下载一个文件)。这不是一个问题,我使用
Timer
Timertask
进行了如下操作:

FileTimer rXMLFileTimer;

private static Timer timer = new Timer("FileReader");
rXMLFileTimer = new ReadFileTimer();
int myDelay = 30;
timer.scheduleAtFixedRate(rXMLFileTimer, 0, myDelay * 1000);
public class Test {

public static class MyJob implements Callable<ReadFileTimer> {

    @Override
    public ReadFileTimer call() throws Exception {
        Timer timer = new Timer("test");

        ReadFileTimer t = new ReadFileTimer();

        int delay = 10;
        // Delay in seconds
        timer.schedule(t, 0, delay * 1000);

        return t;
    }
}

public static void main(String[] args) {

    MyJob job = new MyJob();
    System.out.println(new Date());

    Future<ReadFileTimer> control = Executors.newSingleThreadExecutor().submit(job);

    ReadFileTimer timerTask = null;
    try {
        int maxAmountOfTime = 30;
        timerTask = control.get(maxAmountOfTime, TimeUnit.SECONDS);

    } catch (TimeoutException ex) {
        control.cancel(true);           
    } catch (InterruptedException ex) {

    } catch (ExecutionException ex) {}

    }
}
并且
timertask
将一直运行,直到调用
rXMLFileTimer.cancel()
。到目前为止没有问题

现在,要求该
timertask
应一直运行,直到调用
rXMLFileTimer.cancel()
给定的时间为止

我的第一个方法(不起作用)是实现一个
未来
,如下所示:

FileTimer rXMLFileTimer;

private static Timer timer = new Timer("FileReader");
rXMLFileTimer = new ReadFileTimer();
int myDelay = 30;
timer.scheduleAtFixedRate(rXMLFileTimer, 0, myDelay * 1000);
public class Test {

public static class MyJob implements Callable<ReadFileTimer> {

    @Override
    public ReadFileTimer call() throws Exception {
        Timer timer = new Timer("test");

        ReadFileTimer t = new ReadFileTimer();

        int delay = 10;
        // Delay in seconds
        timer.schedule(t, 0, delay * 1000);

        return t;
    }
}

public static void main(String[] args) {

    MyJob job = new MyJob();
    System.out.println(new Date());

    Future<ReadFileTimer> control = Executors.newSingleThreadExecutor().submit(job);

    ReadFileTimer timerTask = null;
    try {
        int maxAmountOfTime = 30;
        timerTask = control.get(maxAmountOfTime, TimeUnit.SECONDS);

    } catch (TimeoutException ex) {
        control.cancel(true);           
    } catch (InterruptedException ex) {

    } catch (ExecutionException ex) {}

    }
}
公共类测试{
公共静态类MyJob实现了可调用{
@凌驾
public ReadFileTimer调用()引发异常{
定时器=新定时器(“测试”);
ReadFileTimer t=新的ReadFileTimer();
int延迟=10;
//以秒为单位的延迟
定时表(t,0,延迟*1000);
返回t;
}
}
公共静态void main(字符串[]args){
MyJob=新建MyJob();
System.out.println(新日期());
Future control=Executors.newSingleThreadExecutor().submit(作业);
ReadFileTimer timerTask=null;
试一试{
int maxamontoftime=30;
timerTask=control.get(maxamontoftime,TimeUnit.SECONDS);
}捕获(TimeoutException例外){
控件。取消(true);
}捕获(中断异常例外){
}catch(ExecutionException ex){}
}
}
这不起作用,因为我无法在超时发生后调用
timerTask.cancel()
。然后我的问题是:如何在给定的时间内启动
timerTask


谢谢

为什么不加入第二个计时器任务来取消第一个?例如,此代码每秒打印一次日期,持续10秒:

public static void main(String[] args) throws Exception {
    Timer timer = new Timer();
    final TimerTask runUntilCancelledTask = new TimerTask() {
        @Override
        public void run() {
            System.out.println(new Date());
        }
    };
    timer.schedule(runUntilCancelledTask, 0, 1000);
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            runUntilCancelledTask.cancel();
        }
    }, 10000); // Run once after delay to cancel the first task
}

谢谢这比我尝试的要容易得多