如何使用 java 在服务器端实现倒计时触发器?

how to implement countdown trigger in server side using java?

像 quibids 和 ebay 这样的投标网站有一个倒计时,显示拍卖还剩多少时间。我知道这可以在 FE 上得到解决,应该相当容易。我想知道的是如何在服务器端执行此操作?比如发送电子邮件给参加但没有获胜的人,以及在时间到了时更新数据库。我想过两种方法来做到这一点。

  1. 在客户端保留计时器并在第一个请求命中时进行更新
  2. 打开一个新线程并使其休眠 x 时间然后醒来进行更新。

这两种方法对我来说都不合适,并且会导致我认为的问题。就像用户可能无法及时获得更新,或者服务器会有很多睡美人在等待。

What I want to know is how to do this on server side? like sending an email to people participate but didn't win and updating database when times up.

最佳方式可能因服务器端的技术堆栈而异。

如果您 运行 来自 Servlet 容器(例如:Tomcat、Jboss...),您 可能想做类似的事情:Background timer task in JSP/Servlet web application

如果你是运行一个Spring应用程序(例如:Spring Boot或Spring MVC),那么我推荐@Scheduled或其他Task Execution and Scheduling

对于高级场景,您可能需要使用 Quartz

其他,那么你应该尝试将它与 Java Timer Task

挂钩

要安排任务,请使用 ScheduledExecutorService。