定时器程序怎么写

时间:2025-01-28 02:26:12 单机游戏

编写定时器程序的方法取决于你使用的编程语言和具体需求。以下是几种常见编程语言的定时器程序示例:

Python 示例

```python

import time

def timer(seconds):

start_time = time.time()

while True:

elapsed_time = time.time() - start_time

if elapsed_time >= seconds:

print("Time's up!")

break

调用 timer 函数,设置 10 秒后执行

timer(10)

```

Java 示例

```java

import java.util.Scanner;

import java.util.Timer;

import java.util.TimerTask;

public class ShutdownTimer {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("请输入定时关机的时间(单位:秒):");

int shutdownTime = scanner.nextInt();

if (shutdownTime < 0) {

System.out.println("输入的时间不能为负数。");

return;

}

Timer timer = new Timer();

timer.schedule(new TimerTask() {

@Override

public void run() {

System.out.println("关机时间到!");

Runtime.getRuntime().exec("shutdown -s -t " + shutdownTime * 1000);

}

}, shutdownTime * 1000);

System.out.println("定时器已启动,按任意键退出...");

scanner.nextLine();

}

}

```

C 示例

```csharp

using System;

using System.Threading;

class Program {

private static Timer _timer;

static void Main(string[] args) {

// 创建定时器:2秒后开始,每隔1秒执行一次

_timer = new Timer(TimerCallback, null, 2000, 1000);

Console.WriteLine("定时器已启动,按任意键退出...");

Console.ReadKey();

// 释放定时器资源

_timer.Dispose();

}

private static void TimerCallback(object state) {

Console.WriteLine($"当前时间: {DateTime.Now:HH:mm:ss}");

}

}

```

C++ 示例

```cpp

include

include

include

void timer_handler(int signum) {

std::cout << "Timer expired!" << std::endl;

}

int main() {

std::signal(SIGALRM, timer_handler); // 设置定时器,间隔为1秒

alarm(1); // 主程序继续执行

while (1) {

std::cout << "Main program is running..." << std::endl;

std::this_thread::sleep_for(std::chrono::seconds(1));

}

return 0;

}

```

JavaScript 示例(Node.js)

```javascript

function timer(seconds) {

return new Promise((resolve) => {

setTimeout(() => {

console.log("Time's up!");

resolve();

}, seconds * 1000);

});

}

(async () => {

console.log("定时器已启动,按任意键退出...");

await timer(10);

console.log("主程序结束");

})();

```

这些示例展示了如何在不同的编程语言中实现定时器功能。你可以根据自己的需求选择合适的编程语言和实现方式。