【问题标题】:Timer is not working truely定时器不能正常工作
【发布时间】:2016-01-09 12:29:33
【问题描述】:

定时器只工作一次。此服务必须每 2 分钟运行一次... 公共部分类Service1:ServiceBase { RuleContext 实体 = 新 RuleContext(); 私人 int id; 私人定时器_timer; 私有日期时间 _lastRun = DateTime.Now.AddDays(-1);

    public Service1()
    {
        InitializeComponent();
    }



    protected override void OnStart(string[] args)
    {
        OnTimer();
    }

    public void OnTimer()
    {
        Timeout.Infinite);
        _timer = new Timer();
        _timer.Interval = 2 * 60 * 1000;
        _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
        _timer.Enabled = true;
        _timer.AutoReset = true;
        _timer.Start();

    }



    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {

        // ignore the time, just compare the date
        if (_lastRun.Date <= DateTime.Now.Date)
        {


            GetRule();




        }
    }



    protected override void OnStop()
    {
    }

    public void GetRule()
    {



        var query = from ruleset in entity.RuleSets
                    join rule in entity.Rules on ruleset.Id equals rule.RuleSetId
                    join schedulerule in entity.Schedules on rule.ScheduleId equals schedulerule.Id

                    select new
                    {
                        Id = ruleset.Id,
                        daily = schedulerule.Daily,
                        mountly = schedulerule.Monthly,
                        dayofMounth = schedulerule.DayOfMonth,
                    };


        foreach (var q in query.ToList())
        {

            if (q.mountly && q.daily)
            {
                if (q.dayofMounth == (int)DateTime.Now.Day)
                {
                    UpdateValue(q.Id);
                }
            }

            else if (q.daily)
            {
                UpdateValue(q.Id);
            }

            else if (q.mountly)
            {
                if (q.dayofMounth == (int)DateTime.Now.Day)
                {
                    UpdateValue(q.Id);
                }
            }
        }
    }


    public void UpdateValue(int id)
    {
        var ruleSet = entity.RuleSets.First(k => k.Id == id);
        ruleSet.RcvByte = 0;
        ruleSet.SentByte = 0;
        entity.SaveChanges();
    }
}

【问题讨论】:

  • 你不必停止计时器...

标签: c# windows service timer


【解决方案1】:

private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {

    // ignore the time, just compare the date
    if (_lastRun.Date <= DateTime.Now.Date)
    {
        GetRule();

   }
}

由于 AutoReset 属性设置为 true,因此无需停止和启动计时器。

【讨论】:

  • 我试过了,但是定时器只能再工作一次。什么都没有改变。
  • 是的。我想向你展示整个代码。也许这个错误来自 foreach 循环。我不知道。
  • 看来你的定时器代码没有问题。使用 try catch 并检查 GetRule() 方法中发生的任何异常。
【解决方案2】:
_timer.Stop();

这条线导致了这个问题。删除它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多