.NET 幫助

C# 計時器(開發人員如何使用)

介紹

在C#中,計時器類是用於在指定間隔調度執行代碼的強大工具。 無論您正在開發 Windows Form 應用程式還是控制台應用程式,了解如何使用計時器都可以大大提高應用程式的功能性。 本教程將引導您了解在 C# 中使用計時器的基本知識,包括如何設置計時器、處理其事件,以及確保它們在應用程式中順利運行。 我們還將討論如何使用IronPDF 進行 C# 應用程序中的自動化 PDF 生成,以在 C# 中使用計時器自動生成 PDF。

C# 計時器類別介紹

C# Timer(開發人員如何使用):圖 1 - Timer 類別

C# 提供了多種定時器類,每種都適合不同的任務和環境。 最常用的計時器類別是伺服器計時器的System.Timers.Timer和 Windows Forms 應用程式的System.Windows.Forms.Timer。 瞭解事件處理程式的角色在使用計時器類別時至關重要,因為這些處理程式決定了計時器所指示的每個重要時刻所執行的操作,例如滴答聲或經過時間間隔的事件。

設定新計時器

配置計時器的時間間隔是其運行的基礎,決定計時器的事件處理程序被調用的頻率,從而控制應用程式時間敏感功能的節奏。 在 C# 應用程式中使用計時器,特別是在開發 Windows Forms 應用程式時,您可以先從工具箱中將 System.Windows.Forms.Timer 元件添加到表單上,或是以程式化方式建立計時器物件以獲得更大的靈活性。

var timer = new System.Timers.Timer(); // use a timer
timer.Interval = 2000; // Sets the timer interval to tick every 2 seconds
var timer = new System.Timers.Timer(); // use a timer
timer.Interval = 2000; // Sets the timer interval to tick every 2 seconds
Dim timer = New System.Timers.Timer() ' use a timer
timer.Interval = 2000 ' Sets the timer interval to tick every 2 seconds
$vbLabelText   $csharpLabel

此簡單設置創建一個每兩秒滴答一次的計時器。 但是,要讓計時器執行動作,您需要將其連接到事件處理程序。

處理 Elapsed 事件

通過將經過事件處理程序附加到System.Timers.TimerElapsed事件,您可以確保應用程式能夠在每個間隔執行任務,從而有效地回應基於時間的觸發器。 每當計時器的間隔時間過去時,這個事件就會被觸發。 您可以將處理程序附加到此事件,以指定計時器滴答時應發生的情況:

timer.Elapsed += OnTimedEvent;
timer.Elapsed += OnTimedEvent;
timer.Elapsed += OnTimedEvent
$vbLabelText   $csharpLabel

在上述代碼中,OnTimedEvent 是您定義的方法,每當計時器的 Elapsed 事件被觸發時都會被調用。

建立事件處理程式

在定義計時器事件處理器時,您設計一個方法以響應計時器的滴答事件執行,從而可以精確控制在預定間隔採取的行動。 計時器的Elapsed事件的事件處理程式通常看起來像這樣:

static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
    Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}", e.SignalTime);
}
static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
    Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}", e.SignalTime);
}
Shared Sub OnTimedEvent(ByVal source As Object, ByVal e As System.Timers.ElapsedEventArgs)
	Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}", e.SignalTime)
End Sub
$vbLabelText   $csharpLabel

此方法僅在計時器逾時時將當前時間列印到控制台,展示如何響應計時器事件。

啟動和停止計時器

在設定好計時器及其事件處理程序後,您需要啟動計時器。 您可以通過將其Enabled屬性設置為true或調用Start方法來完成:

timer.Enabled = true; // or timer.Start();
timer.Enabled = true; // or timer.Start();
timer.Enabled = True ' or timer.Start();
$vbLabelText   $csharpLabel

要停止計時器,您可以將Enabled設為false或呼叫Stop方法。 這對於防止您的應用程序在不需要時運行不必要的操作至關重要。

在 Windows Forms 應用程式中使用計時器

System.Windows.Forms.Timer 是一個寶貴的 Windows 表單組件,旨在無縫整合到 Windows Forms 應用程式的事件驅動模型中,促進定期動作而不會降低使用者介面的響應能力。

範例:將計時器添加到表單

在 Windows Forms 應用程式中,您可以從工具箱中拖曳計時器控制項到您的表單上,或者以程式方式創建,如下所示:

System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
myTimer.Interval = 1000; // 1 second
myTimer.Tick += new EventHandler(TimerEventProcessor);
myTimer.Start();
System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
myTimer.Interval = 1000; // 1 second
myTimer.Tick += new EventHandler(TimerEventProcessor);
myTimer.Start();
Dim myTimer As New System.Windows.Forms.Timer()
myTimer.Interval = 1000 ' 1 second
AddHandler myTimer.Tick, AddressOf TimerEventProcessor
myTimer.Start()
$vbLabelText   $csharpLabel

在此,TimerEventProcessor 是一個事件處理程序,它會在每次發生 Tick 事件時被調用,這類似於 System.Timers.Timer 中的 Elapsed 事件。

高級計時管理

計時器的執行緒安全性

在使用計時器時,了解應用程式的線程模型至關重要。 System.Timers.TimerSystem.Threading.Timer 在執行緒池執行緒上執行其回調,允許平行執行。 然而,如果您的回調方法修改了共享數據或與用戶界面元素交互,這可能會導致線程安全問題。 若要從計時器的回調安全地更新 UI 元素,您必須使用特定於應用程式類型的技術將回調調度回 UI 執行緒(例如,在 Windows Forms 中使用 InvokeBeginInvoke)。

高精度計時

對於需要高精度計時的應用程式(例如,多媒體應用程式或遊戲),System.Diagnostics.Stopwatch 類別比定時器更適合用於以高精確度測量經過的時間。 雖然Stopwatch類本身不是計時器,但可以與計時器結合使用,以實現精確的時間測量。

實用範例

範例:實現倒數計時器

一個計時器有用的常見情境是創建倒數計時器。 這可以通過將計時器間隔設置為一秒(1000 毫秒),並在計時器每次結束時減少計數器來完成。 當計數器歸零時,計時器會停止,表示倒數結束。

using System;
namespace CountdownApp
{
    class Program
    {
        static int countdownTime = 10; // Countdown from 10 seconds
// public static void main
        public static void Main(string [] args)
        {
            StartCountdown();
            Console.ReadLine(); // Prevent console from closing immediately
        }
        static void StartCountdown()
        {
            var timer = new System.Timers.Timer(1000); // Tick every second, var timer
            timer.Elapsed += UpdateCountdown;
            timer.Enabled = true;
        }
// public static void printtimes
        static void UpdateCountdown(Object source, System.Timers.ElapsedEventArgs e)
        {
            if (countdownTime > 0)
            {
                Console.WriteLine(countdownTime-- + " seconds remaining");
            }
            else
            {
                Console.WriteLine("Countdown finished!");
                ((System.Timers.Timer)source).Stop(); // Stop the timer
            }
        }
    }
}
using System;
namespace CountdownApp
{
    class Program
    {
        static int countdownTime = 10; // Countdown from 10 seconds
// public static void main
        public static void Main(string [] args)
        {
            StartCountdown();
            Console.ReadLine(); // Prevent console from closing immediately
        }
        static void StartCountdown()
        {
            var timer = new System.Timers.Timer(1000); // Tick every second, var timer
            timer.Elapsed += UpdateCountdown;
            timer.Enabled = true;
        }
// public static void printtimes
        static void UpdateCountdown(Object source, System.Timers.ElapsedEventArgs e)
        {
            if (countdownTime > 0)
            {
                Console.WriteLine(countdownTime-- + " seconds remaining");
            }
            else
            {
                Console.WriteLine("Countdown finished!");
                ((System.Timers.Timer)source).Stop(); // Stop the timer
            }
        }
    }
}
Imports System
Namespace CountdownApp
	Friend Class Program
		Private Shared countdownTime As Integer = 10 ' Countdown from 10 seconds
' public static void main
		Public Shared Sub Main(ByVal args() As String)
			StartCountdown()
			Console.ReadLine() ' Prevent console from closing immediately
		End Sub
		Private Shared Sub StartCountdown()
			Dim timer = New System.Timers.Timer(1000) ' Tick every second, var timer
			AddHandler timer.Elapsed, AddressOf UpdateCountdown
			timer.Enabled = True
		End Sub
' public static void printtimes
		Private Shared Sub UpdateCountdown(ByVal source As Object, ByVal e As System.Timers.ElapsedEventArgs)
			If countdownTime > 0 Then
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Console.WriteLine(countdownTime-- + " seconds remaining");
				Console.WriteLine(countdownTime & " seconds remaining")
				countdownTime -= 1
			Else
				Console.WriteLine("Countdown finished!")
				DirectCast(source, System.Timers.Timer).Stop() ' Stop the timer
			End If
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

以下是上述程式碼的輸出:

C# Timer(對開發人員的運作方式):圖2 - 倒數計時器輸出

範例:安排定期資料庫檢查

定時器可以用來定期檢查資料庫,例如查詢新資料或清理舊記錄。 此示例設置了一個計時器,每小時查詢一次資料庫:

private static void SetupDatabaseCheckTimer()
{
    var timer = new System.Timers.Timer(3600000); // Set to 1 hour
    timer.Elapsed += CheckDatabase;
    timer.Enabled = true;
}
private static void CheckDatabase(Object source, System.Timers.ElapsedEventArgs e)
{
    // Perform database operations here
    Console.WriteLine("Database checked at " + e.SignalTime);
}
private static void SetupDatabaseCheckTimer()
{
    var timer = new System.Timers.Timer(3600000); // Set to 1 hour
    timer.Elapsed += CheckDatabase;
    timer.Enabled = true;
}
private static void CheckDatabase(Object source, System.Timers.ElapsedEventArgs e)
{
    // Perform database operations here
    Console.WriteLine("Database checked at " + e.SignalTime);
}
Private Shared Sub SetupDatabaseCheckTimer()
	Dim timer = New System.Timers.Timer(3600000) ' Set to 1 hour
	AddHandler timer.Elapsed, AddressOf CheckDatabase
	timer.Enabled = True
End Sub
Private Shared Sub CheckDatabase(ByVal source As Object, ByVal e As System.Timers.ElapsedEventArgs)
	' Perform database operations here
	Console.WriteLine("Database checked at " & e.SignalTime)
End Sub
$vbLabelText   $csharpLabel

IronPDF 介紹

IronPDF - 輕鬆從 HTML 和 ASPX 生成 PDF 因其簡單易用而備受讚譽,可從 HTML 或 URL 生成 PDF,實際上允許您的應用程式將任何 HTML 內容「列印」成 PDF 文件。 這對於生成報告、發票或任何需要以標準化格式呈現的網頁內容非常有用。 IronPDF還支持高級功能,例如CSS樣式、JavaScript和自定義字體,確保生成的PDF保持網頁內容的忠實度。

IronPDF 的一個顯著特點是其HTML 到 PDF 轉換功能,可以保留佈局和樣式。 它從網路內容生成 PDF,這對於報告、發票和文件是理想的。 HTML 文件、URL 和 HTML 字串可以輕鬆轉換為 PDF。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

安裝 IronPDF

您可以通過執行以下命令,使用 NuGet 封裝管理器安裝 IronPDF:

Install-Package IronPdf

範例

假設您需要生成每日更新資料的 PDF 格式報告。 為了簡化,我們將生成一個基本的 HTML 報告,並使用 IronPDF 每24小時將其轉換為 PDF。 在您的 C# 應用程式中,您將設置 System.Timers.Timer 每 24 小時觸發一次。 需要注意的是,該間隔以毫秒設置,因此24小時表示為24 *_60*_60 * 1000毫秒。

using System;
using System.Timers;
using IronPdf;
using Timer = System.Timers.Timer;
class Program
{
    static void Main(string [] args)
    {
        // Set up the timer for 24 hours
        Timer timer = new Timer(24 * 60 * 60 * 1000);
        timer.Elapsed += OnTimedEvent;
        timer.AutoReset = true;
        timer.Enabled = true;
        Console.WriteLine("Press Enter to exit the program.");
        Console.ReadLine();
    }
    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        GeneratePdfReport();
    }
    private static void GeneratePdfReport()
    {
        var renderer = new HtmlToPdf();
        var pdf = renderer.RenderHtmlAsPdf("<h1>Daily Report</h1><p>This is the automated daily report.</p>");
        string outputPath = $"f:\\DailyReport_{DateTime.Now:yyyyMMdd}.pdf";
        pdf.SaveAs(outputPath);
        Console.WriteLine($"Generated PDF report at {outputPath}");
    }
}
using System;
using System.Timers;
using IronPdf;
using Timer = System.Timers.Timer;
class Program
{
    static void Main(string [] args)
    {
        // Set up the timer for 24 hours
        Timer timer = new Timer(24 * 60 * 60 * 1000);
        timer.Elapsed += OnTimedEvent;
        timer.AutoReset = true;
        timer.Enabled = true;
        Console.WriteLine("Press Enter to exit the program.");
        Console.ReadLine();
    }
    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        GeneratePdfReport();
    }
    private static void GeneratePdfReport()
    {
        var renderer = new HtmlToPdf();
        var pdf = renderer.RenderHtmlAsPdf("<h1>Daily Report</h1><p>This is the automated daily report.</p>");
        string outputPath = $"f:\\DailyReport_{DateTime.Now:yyyyMMdd}.pdf";
        pdf.SaveAs(outputPath);
        Console.WriteLine($"Generated PDF report at {outputPath}");
    }
}
Imports System
Imports System.Timers
Imports IronPdf
Imports Timer = System.Timers.Timer
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Set up the timer for 24 hours
		Dim timer As New Timer(24 * 60 * 60 * 1000)
		AddHandler timer.Elapsed, AddressOf OnTimedEvent
		timer.AutoReset = True
		timer.Enabled = True
		Console.WriteLine("Press Enter to exit the program.")
		Console.ReadLine()
	End Sub
	Private Shared Sub OnTimedEvent(ByVal source As Object, ByVal e As ElapsedEventArgs)
		GeneratePdfReport()
	End Sub
	Private Shared Sub GeneratePdfReport()
		Dim renderer = New HtmlToPdf()
		Dim pdf = renderer.RenderHtmlAsPdf("<h1>Daily Report</h1><p>This is the automated daily report.</p>")
		Dim outputPath As String = $"f:\DailyReport_{DateTime.Now:yyyyMMdd}.pdf"
		pdf.SaveAs(outputPath)
		Console.WriteLine($"Generated PDF report at {outputPath}")
	End Sub
End Class
$vbLabelText   $csharpLabel

輸出

執行程式碼後,將在控制台顯示以下輸出。 在這裡,我修改了程式碼以加快輸出速度,所以我使用了10秒計時器。

C# Timer(開發人員的工作原理):圖3 - 控制台輸出

以下是生成的 PDF:

C# 計時器(它對開發人員的工作原理):圖 4 - PDF 報告

結論

C# 計時器(開發人員如何使用):圖 5 - 授權

總之,將 C# 計時器與 IronPDF 結合使用,為 .NET 應用程式中的 PDF 文件生成和管理提供了一種強大的自動化方法。 通過提供的範例,我們已探討如何設置 C# 計時器以定期觸發 PDF 生成任務,無論是為了頻繁的測試目的還是排程的報告生成。

使用 C# 計時器,我們可以精準控制 PDF 相關任務的執行時間,從而實現定期更新、報表生成或任何需按計畫進行的任務。 IronPDF 增強了這項功能,提供了一種簡單且高效的方法,基於動態內容、HTML,甚至是網頁來創建、操作和保存 PDF 文件。

IronPDF 提供免費試用版與授權資訊,可透過持有授權來獲得完整的訪問權限與支援。 這為您在 .NET 應用程式中實現綜合 PDF 功能提供了一種具有成本效益的方法。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
Graphql C#(開發者如何操作)
下一個 >
Math.Round C#(對開發人員的運作方式)