How to call a method after some specific interval of time in Java

纵然是瞬间 提交于 2019-12-23 16:37:38

问题


Here is the use case:

I am using Java (with Spring)

Once the user (through a web-app) confirms to the subscription, I want to send him an email exactly after 30 mins.

Now how to do this? Do I need a message broker? or something like ScheduledExecutorService? Do I need some sort of queue?

Please advise.


回答1:


Can look into quartz scheduler for this.

By the way a common strategy is to send a bulk of all pending mails in bulk in every 30 minutes or so. Quartz can help in do that as well.




回答2:


You can use the Quartz Scheduler. Its fairly easy to use. You can schedule something every week or ever 30 minutes or whatever you want basically.




回答3:


Create an object for Timer

 private Timer myTimer;

in main method

myTimer = new Timer();
    myTimer.schedule(new TimerTask() {
        @Override
        public void run() {
           //your method
        }

    }, 0, 200);



回答4:


It is not that the thread will die after sending the mail. When you configure Quartz, a new thread will automatically be created and will execute the assigned task on specified interval. Or else you use Timer class also. It is very easy to use.

    Timer timer = new Timer(); // Get timer

    long delay = 30 * 60 * 1000; // 3o min delay

    // Schedule the two timers to run with different delays.
    timer.schedule(new MyTask(), 0, delay);

...................



class MyTask extends TimerTask {

    public void run() {
        // business logic
        // send mail here
    }
}


来源:https://stackoverflow.com/questions/6858573/how-to-call-a-method-after-some-specific-interval-of-time-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!