我想向它添加一个特定的功能,以安排将来在帖子作者指定的日期和时间发布帖子。例如,如果我们从用户那里收到此日期和时间:2020-09-07 14:08:07 .
那么,如何通过使用托管服务只运行一次并更改数据库中的标志并在此之后保存更改来为其安排后台任务?
看来您想在用户指定的日期时间执行后台任务/作业,为了达到要求,您可以尝试使用一些消息队列服务,例如Azure Queue Storage,它使我们能够指定消息多长时间应该通过设置对 Dequeue 和 Peek 操作不可见visibilityTimeout
。
当您的应用程序用户想要创建新帖子并指定发布日期时间时,您可以将新消息(具有基于用户预期日期时间的指定 visibilityTimeout)插入队列,以便新插入的消息仅在指定日期可见排队的时间。
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);
然后你可以实现一个队列触发的后台任务来从队列中检索消息并更新你的数据库记录。
注意:Microsoft Azure Storage Emulator是一个模拟 Azure Queue 等服务用于本地开发和测试目的的工具,您可以尝试在本地针对存储服务测试代码,而无需创建 Azure 订阅或产生任何费用。