代码实现定时功能 - Python、JavaScript、C#示例
在大多数编程语言中,你可以使用定时器或计时器函数来实现定时功能。以下是几种常见的实现方式:\n\n1. Python中使用time模块的sleep函数:\n\npython\nimport time\n\ndef my_function():\n print("定时功能执行")\n\n# 每隔2秒执行一次my_function函数\nwhile True:\n my_function()\n time.sleep(2)\n\n\n2. JavaScript中使用setTimeout函数:\n\njavascript\nfunction myFunction() {\n console.log("定时功能执行");\n}\n\n// 每隔2秒执行一次myFunction函数\nsetInterval(myFunction, 2000);\n\n\n3. C#中使用Timer类:\n\ncsharp\nusing System;\nusing System.Timers;\n\npublic class Program\n{\n public static void Main(string[] args)\n {\n Timer timer = new Timer(2000); // 2000毫秒 = 2秒\n timer.Elapsed += TimerElapsed;\n timer.AutoReset = true; // 设置为true表示定时器会一直循环执行\n timer.Enabled = true; // 启动定时器\n\n Console.ReadLine(); // 阻塞主线程,避免程序退出\n }\n\n private static void TimerElapsed(object sender, ElapsedEventArgs e)\n {\n Console.WriteLine("定时功能执行");\n }\n}\n\n\n以上是三种常见的实现方式,具体的实现方法可能会因编程语言和框架的不同而有所变化。
原文地址: https://www.cveoy.top/t/topic/p79y 著作权归作者所有。请勿转载和采集!