This topic provides the sample code for sending and subscribing to scheduled messages through the Java SDK over TCP.

Scheduled messages are consumed after a specified timestamp. These messages are sent when a time window is required between message production and consumption, or when tasks need to be triggered at a scheduled time.

For the concepts and use precautions of scheduled messages, see Scheduled messages and delayed messages.

Note For new users, we recommend that you read the Demo project to learn how to build a Message Queue for Apache RocketMQ project before sending and subscribing to a message.

Prerequisites

You have completed the following operations:

Send scheduled messages

Note For more information about the sample code, see Message Queue for Apache RocketMQ code library.

The sample code for sending scheduled messages is as follows:

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.PropertyKeyConst;

import com.aliyun.openservices.ons.api.SendResult;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Properties;

public class ProducerDelayTest {
    public static void main(String[] args) {
        Properties properties = new Properties();
        // The AccessKey ID you created in the Alibaba Cloud console for identity authentication.
        properties.put(PropertyKeyConst.AccessKey, "XXX");
        // The AccessKey secret you created in the Alibaba Cloud console for identity authentication.
        properties.put(PropertyKeyConst.SecretKey, "XXX");
        // The TCP endpoint. Go to the Instances page in the Message Queue for Apache RocketMQ console, and view the endpoint in the Endpoint Information section.
        properties.put(PropertyKeyConst.NAMESRV_ADDR,
          "XXX");
        Producer producer = ONSFactory.createProducer(properties);
        // Before sending a message, call the start method once to start the producer.
        producer.start();
        Message msg = new Message( //
                // The topic of the message.
                "Topic",
                // The message tag, which is similar to a Gmail tag. It is used to sort messages, enabling the consumer to filter messages on the Message Queue for Apache RocketMQ broker based on the specified criteria.
                "tag",
                // The message body in any binary format. Message Queue for Apache RocketMQ does not process the message body. The producer and consumer must negotiate consistent serialization and deserialization methods.
                "Hello MQ".getBytes());
        // The message key, which must be globally unique.
        // A unique identifier enables you to query a message and resend it in the console if you fail to receive the message.
        // Note: Messages can still be sent and received even if this attribute is not set.
        msg.setKey("ORDERID_100");

        try {
            // The delivery time of scheduled messages (in ms) after a specific timestamp, for example, 2016-03-07 16:21:00. If the scheduled time is earlier than the current timestamp, the message is immediately delivered to the consumer.
            long timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2016-03-07 16:21:00").getTime();

            msg.setStartDeliverTime(timeStamp);
            // The message sending result, which is successful if no exception occurs.
            SendResult sendResult = producer.send(msg);
            System.out.println("Message Id:" + sendResult.getMessageId());
        }
        catch (Exception e) {
            // The message failed to be sent and must be resent. The system can resend the message or store message data persistently.
            System.out.println(new Date() + " Send mq message failed. Topic is:" + msg.getTopic());
            e.printStackTrace();
        }

        // Destroy the producer object before exiting the application.
        // Note: You can choose not to destroy the producer object.
        producer.shutdown();
    }
}       

Subscribe to scheduled messages

The mode for subscribing to scheduled messages is the same as that for subscribing to normal messages. For more information, see Subscribe to messages.