简体   繁体   中英

run a scheduled task once a day

My requirement is I want to schedule a task that should run once a day.For that I am using following code:

public class setAutoReminder {
    EscalationDAO escalationDAO=new EscalationDAO();
    final  SendMail sendMail=new SendMail();
    public void fetch(){
        Date date=new Date();
        Timer timer = new Timer();


        timer.schedule(new TimerTask(){
            public void run(){
                int number=escalationDAO.getAutoReminder();
                System.out.println(number);
                if(number>0) {
                    sendMail.sendMail();
                }
            }
        },date, 1000000000);
    }
}

but this code runs multiple times.I want it to runs once a day.What should I do?

With Spring (using lombok @Slf4j ):

@Slf4j
@Component
public class SetAutoReminder 
{
    @Autowired
    private EscalationDAO escalationDAO;

    @Autowired
    private SendMail sendMail;

    @Scheduled(cron = "0 0 0 * * *") // everyday at midnight
    public void fetch(){
        final int number = escalationDAO.getAutoReminder();
        log.debug("Today number: {}", number);
        if (number>0) {
           sendMail.sendMail();
        }
    }
}

Tutorial on spring scheduling: springsource blog

If you don't have many scheduled jobs then don't add all the Spring baggage. Keep it simple.

Date date=new Date();
Timer timer = new Timer();

timer.schedule(new TimerTask(){
     public void run(){
          System.out.println("Im Running..."+new Date());
     }
},date, 24*60*60*1000);//24*60*60*1000 add 24 hours delay between job executions.

This will do the stuff.

-Siva

您需要一个调度程序,如Quartz Scheduler

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM