简体   繁体   English

如何实施预定通知服务?

[英]How do I implement a Scheduled Notification service?

How do I implement a Scheduled Notification service that sends alerts to the app's users at their preferred times?如何实施计划通知服务,在应用程序用户的首选时间向其发送警报? For the time being, they are receiving immediate notification;目前,他们正在收到即时通知; however, can someone advise on how I might schedule it?但是,有人可以建议我如何安排吗?

在此处输入图片说明


String emailBody = "Hello,\n" + "\n" + "You have received a new notification " ;
emailService.quickEmail(String.join(" ,", emailList), emailSubject, emailBody);

1. Using ScheduledExecutorService 1. 使用 ScheduledExecutorService

ScheduledExecutorService is an ExecutorService that may perform instructions after a specified delay or on a regular basis. ScheduledExecutorService 是一个 ExecutorService,它可以在指定的延迟后或定期执行指令。 The schedule methods construct tasks with different delays and return a task object that may be used to cancel or check their execution. schedule 方法构造具有不同延迟的任务并返回可用于取消或检查其执行的任务对象。 The scheduleAtFixedRate() and scheduleWithFixedDelay() methods generate and run tasks that run at a fixed rate or with a fixed delay until they are cancelled. scheduleAtFixedRate() 和 scheduleWithFixedDelay() 方法生成并运行以固定速率或固定延迟运行的任务,直到它们被取消。

Here's a class that has a method that creates a ScheduledExecutorService that runs the procedure every second.这是一个类,它具有一个方法,该方法创建一个每秒运行该过程的 ScheduledExecutorService。 :


import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
 
class Main
{
    private static void run() {
        System.out.println("Running: " + new java.util.Date());
    }
 
    public static void main(String[] args)
    {
        ScheduledExecutorService executorService;
        executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.scheduleAtFixedRate(Main::run, 0, 1, TimeUnit.SECONDS);
    }
}

2. Using Timer Class 2. 使用定时器类

Threads can use the Timer class to schedule tasks for later execution in a background thread.线程可以使用 Timer 类来安排任务,以便稍后在后台线程中执行。 Tasks can be scheduled for a single execution or for recurrence at regular intervals.任务可以安排为单次执行或定期重复执行。 The schedule() and scheduleAtFixedRate() functions, respectively, schedule the provided job for repeated fixed-delay and fixed-rate execution. schedule() 和 scheduleAtFixedRate() 函数分别为重复的固定延迟和固定速率执行安排提供的作业。 These approaches are currently overburdened.这些方法目前负担过重。

The following code uses the Timer class to run the method run every second (in Java 8 and above):以下代码使用 Timer 类来运行每秒运行一次的方法(在 Java 8 及更高版本中):

import java.util.Timer;
import java.util.TimerTask;
 
class Main
{
    public static void main(String[] args) throws InterruptedException
    {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("Running: " + new java.util.Date());
            }
        }, 0, 1000);
    }
}

3. Using Guava Library 3. 使用番石榴库

Another option is to utilize Guava's AbstractScheduledService class to do some periodic activities while the application is running.另一种选择是利用 Guava 的 AbstractScheduledService 类在应用程序运行时执行一些定期活动。 Subclasses provide runOneIteration(), as well as the standard startUp() and shutDown() methods, to define one iteration of the job.子类提供 runOneIteration() 以及标准的 startUp() 和 shutdown() 方法来定义作业的一次迭代。

The scheduler() function must be implemented to specify the execution schedule.必须实现 scheduler() 函数以指定执行计划。 Typically, you'll utilise one of AbstractScheduledService's given schedules.通常,您将使用 AbstractScheduledService 的给定计划之一。 Scheduler, either newFixedRateSchedule() or newFixedDelaySchedule(), matching to ScheduledExecutorService's common functions.调度程序,newFixedRateSchedule() 或 newFixedDelaySchedule(),匹配 ScheduledExecutorService 的常用函数。

import com.google.common.util.concurrent.AbstractScheduledService;
 
import java.util.Date;
import java.util.concurrent.TimeUnit;
 
class ScheduledExecutor extends AbstractScheduledService
{
    @Override
    protected void startUp() {
        System.out.println("Job started at: " + new java.util.Date());
    }
 
    @Override
    protected void runOneIteration() throws Exception {
        System.out.println("Running: " + new java.util.Date());
    }
 
    @Override
    protected Scheduler scheduler() {
        // execute every second
        return Scheduler.newFixedRateSchedule(0, 1, TimeUnit.SECONDS);
    }
 
    @Override
    protected void shutDown() {
        System.out.println("Job terminated at: " + new java.util.Date());
    }
}
 
class Main
{
    public static void main(String[] args) throws InterruptedException
    {
        ScheduledExecutor executor = new ScheduledExecutor();
        executor.startAsync();
        Thread.sleep(10000);
        executor.stopAsync();
    }
}

4. Using Quartz Scheduler 4. 使用 Quartz 调度器

We may also make use of the Quartz job scheduling library, which can be used in almost any Java application.我们还可以使用 Quartz 作业调度库,它几乎可以在任何 Java 应用程序中使用。 Quartz may be used to design simple or complicated schedules for running tens, hundreds, or even thousands of jobs, jobs whose activities are described as standard Java components that can perform almost whatever you want them to do. Quartz 可用于设计简单或复杂的调度来运行数十、数百甚至数千个作业,这些作业的活动被描述为标准 Java 组件,几乎可以执行您希望它们执行的任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Spring Web Service中实现计划任务? - How to Implement Scheduled Task in Spring Web Service? 如何在Spring中实现自己的@Tranactional感知服务 - How do I implement my own @Tranactional aware service in Spring 如何让这个定时器服务类处理“预定时间的变化”? - How to I make this Timer Service Class handle the “change in scheduled time”? 适用于 Android 的 Azure 通知中心:如何使用后台服务处理数据消息? - Azure Notification Hubs for Android: How do I handle Data-Messages with a Background-Service? 如何停止执行计划数据库备份的守护程序线程? - How do I stop a daemon thread that does scheduled database backup ? 如果发生异常,如何重新启动预定线程? - How do I restart a scheduled thread if an exception occurs? 我如何在春季获得一份预定的石英工作清单? - How do I get a list of scheduled quartz job in spring? 如何对 Spring @Scheduled 任务进行性能和负载测试 - How can I do Performance & Load Testing for Spring @Scheduled task 如何在计划的春季任务之间保持价值 - How do I maintain values between spring task scheduled 如何在JAVA中实现对调度线程的等待和通知 - How to implement wait and notify on Scheduled thread in JAVA
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM