如何在控制台应用程序中每隔12小时执行一个方法

本文关键字:执行 方法 一个 12小时 控制台 应用程序 | 更新日期: 2023-09-27 18:05:44

要求是每12小时之后调用一个方法。方法调用下面的代码应该在不同的线程中继续运行,我们如何实现这一点?

void ExecuteAfterTimeInterval()
{
  //some code
}
public static void main(string[] args)
{
  //call the below method after every 12 hours
  ExecuteAfterTimeInterval();

// run the below code in separate thread
  // some code here 
  //some code here
  //some code here
}

如何在控制台应用程序中每隔12小时执行一个方法

试试吧。查找//设置断点并运行

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace MyConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            Program console = new Program();
            console.MyMethodAsync();
        }
        void ExecuteAfterTimeInterval()
        {
            //some code
        }
        public async Task MyMethodAsync()
        {
            Task<int> longRunningTask = LongRunningOperationAsync();
            // run the below code in separate thread
            //some code here 
            //some code here
            for (int i = 0; i < 10000000000; i++)
            {
                Console.WriteLine(i); //SET BREAK POINT HERE
            }
            //some code here
            //and now we call await on the task 
            int result = await longRunningTask;
        }
        public async Task<int> LongRunningOperationAsync() // assume we return an int from this long running operation 
        {
            bool retry = true;
            using (AutoResetEvent wait = new AutoResetEvent(false))
            {
                while (retry)
                {
                    //Do Work here
                    //await Task.Delay(43200000); //12 hour delay
                    await Task.Delay(3000); //SET BREAK POINT HERE
                }
            }
            return 1;
        }
    }
}