每 x 分钟运行一段代码

编程入门 行业动态 更新时间:2024-10-28 20:27:50
本文介绍了每 x 分钟运行一段代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试编写一个程序,它每 x 分钟执行一次操作.我一直在试验秒表功能,但它似乎没有在时间到时运行我想要的代码.

I'm trying to make a program whereby it does something every x minutes. I have been experimenting with the Stopwatch function but it don't seem to run the code I want when the time is up.

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;

namespace Testing
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch testing = new Stopwatch();
            testing.Start();

            Thread.Sleep(6001);
            TimeSpan ts = testing.Elapsed;
            int timer = Convert.ToInt32(String.Format("{0}", ts.Seconds));
            Console.Write(timer);

            while (testing.Elapsed < TimeSpan.FromMinutes(8))
            {

                timer = Convert.ToInt32(String.Format("{0}", ts.Seconds));
                if (timer % 60 == 0)
                {
                    //run x code every 1 minutes
                    Console.WriteLine("1 min" + timer);
                }


                timer = Convert.ToInt32(String.Format("{0}", ts.Seconds));
                if (timer % 120 == 0)
                {
                    //run x code every 2 minutes
                    Console.WriteLine("2 min" + timer);
                }
            }    

            testing.Stop();
        }
    }
}

推荐答案

根据 xxbbcc 的建议,这里是使用 ManualResetEvent.WaitOne() 和 TimeOut 的实现:

As suggested by xxbbcc, here's an implementation using ManualResetEvent.WaitOne() with a TimeOut:

    static void Main(string[] args)
    {
        int TimeOut = (int)TimeSpan.FromMinutes(2).TotalMilliseconds;
        System.Threading.ManualResetEvent mreDuration = new System.Threading.ManualResetEvent(false);
        Task.Run(() => {
            System.Threading.Thread.Sleep((int)TimeSpan.FromMinutes(30).TotalMilliseconds);
            mreDuration.Set();
        });
        while(!mreDuration.WaitOne(TimeOut))
        {
            Console.WriteLine("Two Minutes...");
        }
        Console.WriteLine("Thirty Mintues!");
        Console.ReadLine();
    }

这篇关于每 x 分钟运行一段代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 11:21:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1393170.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!