I want to add a specific functionality to it to schedule publishing a post in the future in a date and time specified by post author.For example, if we receive this date and time from user : 2020-09-07 14:08:07 .
Then, how can I schedule a background task for it by using hosted services to run only for one time and to change a flag in database and save changes after that?
It seems that you'd like to execute a background task/job at a user specified datetime, to achieve the requirement, you can try to use some message queue services, such as Azure Queue Storage, which enable us to specify how long the message should be invisible to Dequeue and Peek operations by setting visibilityTimeout
.
While your application user want to create a new post and specify a publishing date time, you can insert a new message (with specified visibilityTimeout based on user expected datetime) into the queue, so that this new inserted message would be only visible at specified date time in the queue.
QueueClient theQueue = new QueueClient(connectionString, "mystoragequeue");
if (null != await theQueue.CreateIfNotExistsAsync())
{
//The queue was created...
}
var newPost = "Post Content Here";
var user_specified_datetime = new DateTime(2020, 9, 9, 20, 50, 25);
var datetime_now = DateTime.Now;
TimeSpan duration = user_specified_datetime.Subtract(datetime_now);
await theQueue.SendMessageAsync(newPost, duration, default);
Then you can implement a queue triggered background task to retrieve message(s) from the queue and update your database record(s).
Note: Microsoft Azure Storage Emulator is a tool that emulates the Azure Queue etc services for local development and testing purposes, you can try to test code against the storage services locally without creating an Azure subscription or incurring any costs.