Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

i have one problem with java scheduler,my actual need is i have to start my process at particular time, and i will stop at certain time ,i can start my process at specific time but i can't stop my process at certain time ,how to specify the process how long to run in scheduler,(here i will not put while ) any one have suggestion for that.

import java.util.Timer;
import java.util.TimerTask;
import java.text.SimpleDateFormat;
import java.util.*;
public class Timer
{
    public static void main(String[] args) throws Exception
    {

                  Date timeToRun = new Date(System.currentTimeMillis());
                  System.out.println(timeToRun);
                  Timer timer1 = new Timer();
                  timer1.schedule(new TimerTask() 
                   { 
                     public void run() 
                               {

                        //here i call another method
                        }

                    } }, timeToRun);//her i specify my start time


            }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
481 views
Welcome To Ask or Share your Answers For Others

1 Answer

You could use a ScheduledExecutorService with 2 schedules, one to run the task and one to stop it - see below a simplified example:

public static void main(String[] args) throws InterruptedException {
    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);

    Runnable task = new Runnable() {
        @Override
        public void run() {
            System.out.println("Starting task");
            scheduler.schedule(stopTask(),500, TimeUnit.MILLISECONDS);
            try {
                System.out.println("Sleeping now");
                Thread.sleep(Integer.MAX_VALUE);
            } catch (InterruptedException ex) {
                System.out.println("I've been interrupted, bye bye");
            }
        }
    };

    scheduler.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS); //run task every second
    Thread.sleep(3000);
    scheduler.shutdownNow();
}

private static Runnable stopTask() {
    final Thread taskThread = Thread.currentThread();
    return new Runnable() {

        @Override
        public void run() {
            taskThread.interrupt();
        }
    };
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...