All Products
Search
Document Center

ApsaraMQ for RocketMQ:Send and receive scheduled messages

Last Updated:Aug 18, 2023

This topic provides sample code on how to send and receive scheduled messages by using the TCP client SDK for .NET. Scheduled messages are supported in the Internet, China (Hangzhou), China (Beijing), China (Shanghai), and China (Shenzhen) regions.

Scheduled messages are consumed after a predefined timestamp. Scheduled messages can be used in scenarios in which a time window between message production and message consumption is required, or scenarios in which scheduled tasks are triggered by messages.

For information about the terms that are used for scheduled messages and the precautions that you must take when you use scheduled messages, see Scheduled messages and delayed messages.

Prerequisites

  • The SDK for .NET is downloaded. For more information, see Release notes.

  • The environment is prepared. For more information, see Prepare the environment.

  • The resources that you want to specify in the code are created in the ApsaraMQ for RocketMQ console. The resources include instances, topics, and consumer groups. For more information, see Create resources.

  • The AccessKey pair of your Alibaba Cloud account is obtained. For more information, see Create an AccessKey pair.

Send scheduled messages

Note

For information about the sample code, see ApsaraMQ for RocketMQ code repository.

The following sample code provides an example on how to send scheduled messages by using the HTTP client SDK for .NET:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using ons;

namespace ons
{
    class onscsharp
    {
        private static readonly DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        public static long CurrentTimeMillis()
        {
           return (long) (DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
        }    
       
        static void Main(string[] args)
        {
            // The parameters that are required to create and use the producer. 
            ONSFactoryProperty factoryInfo = new ONSFactoryProperty();
            // The ID of the consumer group that you created in the ApsaraMQ for RocketMQ console. 
            factoryInfo.setFactoryProperty(ONSFactoryProperty.ProducerId, "XXX ");
            // The TCP endpoint. You can obtain the endpoint in the TCP Endpoint section of the Instance Details page in the ApsaraMQ for RocketMQ console. 
            factoryInfo.setFactoryProperty(ONSFactoryProperty.NAMESRV_ADDR, "XXX");
            // The topic that you created in the ApsaraMQ for RocketMQ console. 
            factoryInfo.setFactoryProperty(ONSFactoryProperty.PublishTopics, "XXX");
            // The message content. 
            factoryInfo.setFactoryProperty(ONSFactoryProperty.MsgContent, "XXX");
            // Make sure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are configured. 
            // The AccessKey ID that is used for authentication. 
            factoryInfo.setFactoryProperty(ONSFactoryProperty::AccessKey, getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
	          // The AccessKey secret that is used for authentication. 
            factoryInfo.setFactoryProperty(ONSFactoryProperty::SecretKey, getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            
            // Create the producer. 
            Producer pProducer = ONSFactory.getInstance().createProducer(factoryInfo);

            // Before you send the message, call the start() method only once to start the producer. 
            pProducer.start();

            Message msg = new Message(
                // The message topic. 
                factoryInfo.getPublishTopics(),
                // The message tag. 
                "TagA",
                // The message body. 
                factoryInfo.getMessageContent()
            );

            // The message key. A key is the business-specific attribute of a message and must be globally unique whenever possible. 
            // If you cannot receive a message as expected, you can use the key to query the message in the ApsaraMQ for RocketMQ console. 
            // Note: You can send and receive a message even if you do not specify the key. 
            msg.setKey("ORDERID_100");

            // The delivery time. Unit: ms. A message is consumed only after the specified time. In this example, the message is consumed after 3 seconds. 
            long deliverTime = CurrentTimeMillis() + 3000;
            msg.setStartDeliverTime(deliverTime);

            // Send the message. If no exception is thrown, the message is sent. 
            try
            {
                SendResultONS sendResult = pProducer.send(msg);
            }
            catch(ONSClientException e)
            {
                // The logic for handling failures. 
            }

            // Before you exit your application, destroy the producer. If you do not destroy the producer, issues such as memory leaks may occur. 
            pProducer.shutdown();

        }
    }
}           

Subscribe to scheduled messages

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