ASP .net Core IHostedService定时(每日)后台任务并非每天在Amazon Ec2上运行

时间:2019-04-13 07:01:25

标签: c# amazon-web-services asp.net-core amazon-ec2 amazon-elastic-beanstalk

我正在使用Asp.net Core Timed后台任务在Amazon ElasticBeanstalk Ec2 t2.micro实例上的站点上运行日常任务

代码来自Docs

public Task StartAsync(CancellationToken cancellationToken)
{

        DateTime now = DateTime.Now;

        DateTime Daily= DateTime.Today.AddHours(8.0);


        if (now > Daily)
        {
            Daily= Daily.AddDays(1.0);
        }
        var mylog = Path.Combine(Path.GetTempPath(), "mylog.txt");
        var logs = new List<string>();
        logs.Add(Daily.ToString());            
        var timeToGo = Daily- now;
        logs.Add(timeToGo.ToString());
        File.AppendAllLines(mylog, logs);
        _timer = new Timer(DoWorkAsync, null, timeToGo,
            TimeSpan.FromDays(1));

        return Task.CompletedTask;
    }

    private async void DoWorkAsync(object state)
    {
        var mylog = Path.Combine(Path.GetTempPath(), "mylog.txt");
        var logs = new List<string>();
        logs.Add("Resync started at" + DateTime.UtcNow.ToString("s"));

        File.AppendAllLines(mylog, logs);
        //my task here
     }

但是我对任务的记录显示StartAsync是随机重复的,而DoWorkAsync实际上没有运行

这是DoWorkAsync不在预期时间内运行时的两个日志样本

4/12/2019 8:00:00 AM <---- when next task will run
05:34:46.1320712     <---- time remaining to run it
4/12/2019 8:00:00 AM <---- that means StartAsync had runned again
02:25:30.0774712
4/12/2019 8:00:00 AM
01:00:23.8784953
4/12/2019 8:00:00 AM
00:21:29.8735978  <---- it should run after this line but no record
4/13/2019 8:00:00 AM
23:43:40.0857128
4/13/2019 8:00:00 AM

这是DoWorkAsync运行后的另一个日志示例

4/11/2019 8:00:00 AM
00:48:47.3551756
4/11/2019 8:00:00 AM
00:17:53.6569079
Resync started at2019-04-11T08:00:00 <---- this message is from DoWorkAsync
other logs of my task
4/12/2019 8:00:00 AM
23:23:28.4222248
4/12/2019 8:00:00 AM
22:29:50.2246145
4/12/2019 8:00:00 AM

我不知道这是AWS Ec2问题还是IHostedService,以及什么合适的解决方案

0 个答案:

没有答案