每隔几分钟(或几秒钟)运行@Schedule注释

csc*_*aba 23 java schedule ejb

我想尝试以下列方式使用@Schedule注释:

public class MyTestServlet extends HttpServlet {
    private static JcanLogger LOG = JcanLoggerFactory.getLogger(ServiceTestServlet.class);

    @EJB CronService cronService;

    public void service(HttpServletRequest req, HttpServletResponse resp) throws .... {
    ....
    cronService.iLive(); 
}
---
    @Local // because the ejb is in a servlet (there is no other jvm)
public interface CronService {

    public void iLive();
    public void runsEveryMinute();
}
---
@Singleton
public class CronServiceBean implements CronService {
    private static final JcanLogger LOG = JcanLoggerFactory.getLogger(CronServiceBean.class);

    @Schedule(minute="*")
    public void runsEveryMinute() {
        LOG.info(" runs EveryMinute ");
    }

    public void iLive() {
        LOG.info("iLive");

    }
 ---
 LOG
 ... 
 CronServiceBean:34  ] iLive
Run Code Online (Sandbox Code Playgroud)

根据日志,CronService可以正常运行,但是计划任务'runsEveryMinute'不起作用.

如何使用EJB计划任务?

Bre*_*ail 68

按照该Javadoc中@Schedule注释,默认值是:

  • *对于除小时,分钟和秒之外的所有字段; 和
  • 0 默认情况下为小时,分钟和秒.

通过指定minute="*"并将小时保留为默认值0,它会要求计时器在午夜后每分钟运行一小时(即00:00,00:01,00:02,...,00:59)然后不再运行直到第二天.相反,使用:

@Schedule(hour="*", minute="*")
Run Code Online (Sandbox Code Playgroud)

要每隔几秒(例如,10秒)运行,您可以使用类似cron的语法:

@Schedule(hour = "*", minute = "*", second = "*/10", persistent = false)
Run Code Online (Sandbox Code Playgroud)

默认情况下,调度程序会保留事件.persistent = false如果需要,设置将阻止它们随着时间的推移而累积.


Rad*_*unj 23

请查找以下有关调度程序配置的详细信息。

(1) 每1分钟运行一次

@Schedule(hour = "*", minute = "*/1", persistent = false)
Run Code Online (Sandbox Code Playgroud)

(2) 每5分钟运行一次

@Schedule(hour = "*", minute = "*/5", persistent = false)
Run Code Online (Sandbox Code Playgroud)

(3) 每30秒运行一次

@Schedule(hour = "*", minute = "*", second = "*/30", persistent = false)
Run Code Online (Sandbox Code Playgroud)

(4) 每天早上 6:00 运行

@Schedule(hour = "6", minute = "0", second = "0", persistent = false)
Run Code Online (Sandbox Code Playgroud)

(5) 每周五下午2:00运行

@Schedule(dayOfWeek = "Fri", hour = "14", persistent = false)
Run Code Online (Sandbox Code Playgroud)

(6) 每月第一天早上 5:00 运行

@Schedule(dayOfMonth="1", hour = "5", persistent = false)
Run Code Online (Sandbox Code Playgroud)

我希望这些信息能帮助您根据您的要求配置调度程序。