1

私はTimerTaskを使用してバックグラウンドプロセスを実行しています..

schedule(TimerTask task, long delay, long period) 

タスクを中断せずに長期間の値を変更したいのですが、次の実行サイクルからは変更された時間を使用する必要があります..

中断せずにそれは可能ですか、それとも timerTask をキャンセルして再起動する必要がありますか?

4

1 に答える 1

0

実行中のタスクの間隔を変更できるとは思いませんが、問題に取り組むためにこれを思い付きました。これは実際には Java コンソール プログラムであり (私は Linux しか持っておらず、自宅で BlackBerry 環境を使用できないため)、単一のファイル内で動作させるためだけにプライベートな静的クラスを使用しましたが、このアイデアはすべきだと思います明確にしてください:

import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;


public class Main
{
    public static void main(String[] args)
    {
        //Start a new task which runs every 1000ms
        TimerTest test = new TimerTest(1000L);
        TimerTaskStarter.startTask(test);

        //Wait for enter
        Scanner sc = new Scanner(System.in);
        while(!sc.nextLine().equals(""));

        //Change the interval (actually starts a new TimerTest after the current one runs next time)
        //since there's a new instance involved, the return value needs to be stored so it can be cancelled/controlled
        test = test.changeIntervalAtNextRun(500);

        //Wait for another enter        
        while(!sc.nextLine().equals(""));
        test.cancel();
        System.exit(0);
    }

    private static class TimerTaskStarter
    {
        public static void startTask(TimerTest task)
        {
            //Basic Timer-stuff
            Timer timer = new Timer();
            timer.schedule(task, task.getInterval(), task.getInterval());
        }
    }

    private static class TimerTest extends TimerTask
    {
        /**
         * Current interval
         */
        private long interval;

        /**
         * Flag to indicate interval change at next run
         */
        private boolean changeInterval;

        /**
         * The new instance running with the new interval once started
         */
        private TimerTest nextInstance;


        public TimerTest(long interval)
        {
            this.interval = interval;
            changeInterval = false;
        }

        @Override
        public void run()
        {   
            //The actual thing this task does goes here
            System.out.println("Running task");

            if(changeInterval == false)
            {
                //Not changing interval, just keep running
                System.out.println("Current interval is " + interval);
            }
            else
            {
                //Changing interval, cancel self and start new task
                System.out.println("Startingting new instance with interval " + interval);
                cancel();

                //Start a new task with new interval
                TimerTaskStarter.startTask(nextInstance);
            }
        }

        /**
         * Creates a new task with given interval. This task is cancelled and new task is automatically started
         * the next time this task runs
         * @param newInterval   Interval to run the new instance at
         * @return new TimerTest-instance
         */
        public TimerTest changeIntervalAtNextRun(long newInterval)
        {
            interval = newInterval;
            changeInterval = true;
            nextInstance = new TimerTest(interval);
            return nextInstance;
        }

        /**
         * Returns current interval
         * @return Interval as milliseconds
         */
        public long getInterval()
        {
            return interval;
        }
    }
}

TimerTaskそのため、 ( ) を拡張するクラスTimerTestは、それ自体の別のインスタンスを作成できます。このインスタンスは、次にタスク自体が実行されるときに、要求された間隔で開始されます。changeIntervalAtNextRun現在のタスクが次に実行されるときに自動的に開始される新しいインスタンスを返します。現在のタスクもその時点でキャンセルされます。

物事を単純にするために staticを作成TimerTaskStarter.startTaskしました。これは、現在実行中のすべてのタスクを保持するある種のマネージャー クラスであり、 TimerTest'schangeIntervalAtNextRunに渡すことができ、TimerTest-instance は新しいタスクを直接それに渡します。複数のスレッドでは、おそらく何らかの同期も必要になるでしょうが、この例では考慮していません。これが役に立てば幸いです(ただし、質問は数か月前のものです)。

于 2011-05-15T10:14:24.707 に答える