我正在尝试设置一种方法,该方法将由服务器在特定时间自动运行。例如,每周五上午 9 点向联系人发送电子邮件的方法。我看到了服务器首次启动时运行的方法,并且想知道我想做的事情是否可行。如果可能的话,有人可以指出我可以从哪里开始阅读如何执行此操作。任何帮助将不胜感激。
I am trying to set up a method that will be automatically run by the server at a specific time. For instance, a method that sends out emails to contacts every Friday at 9.00 am. I have seen methods that are run when the server is first started and was wondering if what I want to do is possible. If it is possible, can someone point me to where I can start reading up how to do this. Any help will be highly appreciated.
发布评论
评论(3)
有一个优秀的库 quartz 可以帮助您在应用程序中创建计划任务。例如,请参阅 o 的 Java 中的作业调度 指南'赖利。
There is an excellent library quartz which can help you create scheduled tasks within your application. See e.g., the Job Scheduling in Java guide by o'reilly.
如果您确实想手动执行此操作(而不是使用 Quartz 等特定工具),您可以使用 定时器,它会在应用程序部署时创建,并在应用程序销毁时取消,使用 ServletContextListener 在 web.xml 中声明。
不过,如果您的应用程序集群在多个服务器上,请做好应对额外复杂性的准备。
If you really want to do it manually (and not use specific tools like Quartz), you could use a Timer, which would be created when the application is deployed and canceled when the application is destroyed, using a ServletContextListener declared in your web.xml.
Be prepared for additional complexity if your application is clustered on multiple servers, though.
我还建议使用 Quartz,正如 Johan 已经建议的那样,它是 Java 应用程序中作业调度的成熟解决方案,并且还允许在数据库中进行中央作业存储以及多个 Tomcat 实例的集群。
如果您的 Web 应用程序使用 Spring 框架,您可以使用 内置调度支持。
I also recommend using Quartz as Johan already suggested, it is a well-established solution for job scheduling in Java applications and also allows for central job storage in a database and clustering of multiple Tomcat instances.
In case your web application uses the Spring Framework, you could instead use the built-in scheduling support instead.