How to call a method on specific time in java?

前端 未结 9 1724
Happy的楠姐
Happy的楠姐 2020-11-27 04:43

Is it possible to call a method in java at specific time? For example of I have a piece of code like this:

class Test{

    public static void main(String ar         


        
相关标签:
9条回答
  • 2020-11-27 05:28

    As I know you can use Quartz-scheduler for this. I have not used it yet, but many people have recommended it to me.

    0 讨论(0)
  • 2020-11-27 05:29

    Using a java.util.Timer class you can create a timer and schedule it to run at specific time.

    Below is the example:

    //The task which you want to execute
    private static class MyTimeTask extends TimerTask
    {
    
        public void run()
        {
            //write your code here
        }
    }
    
    public static void main(String[] args) {
    
        //the Date and time at which you want to execute
        DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = dateFormatter .parse("2012-07-06 13:05:45");
    
        //Now create the time and schedule it
        Timer timer = new Timer();
    
        //Use this if you want to execute it once
        timer.schedule(new MyTimeTask(), date);
    
        //Use this if you want to execute it repeatedly
        //int period = 10000;//10secs
        //timer.schedule(new MyTimeTask(), date, period );
    }
    
    0 讨论(0)
  • 2020-11-27 05:29

    Its is possible, and I would use a library such as http://quartz-scheduler.org/

    Quartz is a full-featured, open source job scheduling service that can be integrated with, or used along side virtually any Java EE or Java SE application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components that may execute virtually anything you may program them to do.

    0 讨论(0)
提交回复
热议问题