Hello world, but with scheduled email sending

Prev Next

Goal

We want to add scheduled email sending to an Hello World Application already hosted on Poja. Our goal is to automatically send a daily email to a specified email address using Poja’s Scheduled Tasks feature.

How-to in 2 steps

Step 1: Implement the email sending code

Because Scheduled Tasks are asynchronous, we first have to implement the email sending feature as standard for asynchronous tasks.

Let’s update our configuration’s Queues Nb to enable scheduled tasks:

Next let’s create our Event class and event consumer:

package com.example.demo.endpoint.event.model;

import java.time.Duration;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

@AllArgsConstructor
@Builder(toBuilder = true)
@Data
@EqualsAndHashCode(callSuper = false)
@ToString
public class EmailUpdateTriggered extends PojaEvent {
  @Override
  public Duration maxConsumerDuration() {
    return Duration.ofSeconds(20);
  }

  @Override
  public Duration maxConsumerBackoffBetweenRetries() {
    return Duration.ofMinutes(1);
  }
}
package com.example.demo.service.event;

import com.example.demo.endpoint.event.model.EmailUpdateTriggered;
import com.example.demo.mail.Email;
import com.example.demo.mail.Mailer;
import jakarta.mail.internet.InternetAddress;
import java.util.List;
import java.util.function.Consumer;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor
public class EmailUpdateTriggeredService implements Consumer<EmailUpdateTriggered> {
  private final Mailer mailer;

  @SneakyThrows
  @Override
  public void accept(EmailUpdateTriggered emailUpdateTriggered) {
    var recipientAddress = new InternetAddress("your@email.com");
    mailer.accept(
        new Email(
            recipientAddress,
            List.of(),
            List.of(),
            "",
            "Here is your automatic daily email update !",
            List.of()));
  }
}

To trigger a deployment, just commit and push the code to the preprod branch of the repository.

Step 2: Make the email sending automatic everyday

Now that we have our email sending code, all we have to do is to update our configuration using the Scheduled Tasks menu:

Poja Scheduled Tasks configuration

  • Name: the name of your scheduled task

  • Class name: the exact class name of your asynchronous event, here EmailUpdateTriggered

  • Description: what does your scheduled task do

  • Scheduled expression: refers to the time or interval of execution of your scheduled task, refer to this documentation for further information, here cron(0 6 * * ? *) means every day at 6:00 AM UTC

  • Event stack source: refers to the Queue and the Workers that will process your asynchronous event

Save the configuration and wait for the deployment to complete, and voilà!