maven 使方法在应用程序启动时连续运行

k10s72fa  于 2023-03-07  发布在  Maven
关注(0)|答案(1)|浏览(144)

我在尝试完成的一些事情上遇到了一点麻烦。我有一个使用Java19和Springboot的应用程序,它是在本地托管的(但最终将托管在其他地方)。我有一个SQL数据库设置在相同的。我希望能够向用户发送电子邮件,基于他们正在参与的事件的截止日期。我有一些方法允许我使用JPA查询来查找这些电子邮件,我遇到的问题实际上是调用这些方法。2我希望这些方法总是以5分钟的间隔运行(也就是说,我希望方法每5分钟左右查询一次DB)。有没有办法做到这一点?到目前为止,任何对仓库的调用都是由前端的事件触发的,并且我不确定如何连续调用这些方法?请在下面找到这些方法:

mport java.util.Timer;

//Main class
public class SchedulerMain {
    
    
    
    
    //Timer for 7 days
    public static Boolean sevenDays() throws InterruptedException {

        Timer time = new Timer(); // Instantiate Timer Object
        ScheduledTaskSevenDays st = new ScheduledTaskSevenDays(); // Instantiate SheduledTask class
        time.schedule(st, 0, 300000); // Create Repetitively task for every 5 minutes
        
        return true;
    
    }
}

public class ScheduledTaskSevenDays extends TimerTask {

    @Autowired
    private AdminService adminService;

    // To run for 7 days
    public void run() {
        //Going to call on method here to gather participants and send email
        adminService.SevenDayNotification();
    }
}

 public boolean SevenDayNotification() { 
        System.out.println("Start of email Method");
         try {
             
             
             //Get Survey Participation from DB
             List<String> surveyParticipation;
             surveyParticipation = surveyParticipationRepository.findAllParticipantEmailSevenDays();
             System.out.println("we have a list of participants");
 
             //send emails to all participants in the survey
             for(int i = 0; i<surveyParticipation.size(); i++)
             {
                 System.out.println("im in the loop");
                 emailService.sendMessage(surveyParticipation.get(i), "Notice: Survey will end soon", "This survey is set to end in 7 days, please be sure to complete and submit it before the due date." );
             }
             System.out.println("we are returning true");
             //return true if successful
             return true;
            
         }
         catch(Exception e){
             //return false if unsuccessful
             System.out.println("I have failed at sending email");
             System.out.println(e.getMessage());
             return false;
         }
     }
w51jfk4q

w51jfk4q1#

可以使用@Scheduled注解。
在主应用程序类中,您需要首先启用调度。

@SpringBootApplication
@EnableScheduling
public class MyApplication {
    // ...
}

然后,将@Scheduled添加到某个组件的方法中。

import org.springframework.stereotype.Component;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.concurrent.TimeUnit;
@Component 
public class MyTask {
    @Scheduled(fixedDelay = 5, timeUnit = TimeUnit.MINUTES)
    public void run() {
        // execute periodic task
    }
}

相关问题