跳至頁尾內容
.NET 幫助

C# 定時器(開發者運作原理)

C# 中的計時器類是強大的工具,用來排程在指定的時間間隔執行程式碼。 無論您是在開發 Windows Form 應用程式或 Console App,瞭解如何使用 imer 都能大幅提升應用程式的功能。 本教學將介紹在 C# 中使用計時器的基本知識,包括如何設定計時器、處理其事件,以及確保計時器在應用程式中順利運作。 我們還將討論如何使用 IronPDF 在 C# 應用程式中自動產生 PDF 來使用 C# 中的 Timer 自動產生我們的 PDF。

C# 中的計時器類簡介;

C# Timer (How It Works For Developers):圖 1 - 計時器類

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

設定新的計時器

設定計時器的時間間隔是其運作的基礎,可決定計時器事件處理器被呼叫的頻率,進而控制應用程式中時間敏感功能的節奏。 若要在 C# 應用程式中使用計時器,尤其是在開發 Windows 表單應用程式時,您可以先將工具箱中的 System.Windows.Forms.Timer 元件加入表單中,或是以程式化的方式建立計時器物件,以獲得更大的彈性。

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

這個簡單的設定會建立一個每 2 秒滴答一次的計時器。 然而,若要計時器執行動作,您需要將其連接到事件處理程式。

處理失效事件

透過將已失效事件處理程式附加至 System.Timers.TimerElapsed 事件,您可確保您的應用程式能在每個間隔執行任務,有效回應以時間為基礎的觸發器。 每次計時器的時間間隔過後,都會啟動此事件。 您可以將處理器附加至此事件,以指定當計時器滴答作響時應該發生的事情:

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

在上述程式碼中,OnTimedEvent 是您定義的方法,每當觸發計時器的 Elapsed 事件時,該方法就會被呼叫。

建立事件處理程式

在定義計時器事件處理器時,您會精心設計一個方法,以回應計時器的 tick 事件,從而精確控制在預定義的時間間隔內執行的動作。 計時器 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);
}
$vbLabelText   $csharpLabel

每當計時器過時,此方法只需將目前時間列印到控制台,示範如何回應計時器事件。

啟動和停止計時器

設定完計時器及其事件處理器後,您需要啟動計時器。 您可以將其 Enabled 屬性設定為 true 或呼叫 Start 方法:

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

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

在 Windows 窗體應用程式中使用計時器。

System.Windows.Forms.Timer是一個非常有價值的 Windows 窗體元件,其設計目的在於與 Windows 窗體應用程式的事件驅動模型無縫整合,在不影響使用者介面反應速度的情況下促進定期動作。

範例:在表單中加入計時器。

在 Windows 窗體應用程式中,您可以從工具箱中拖曳計時器控制項到您的窗體上,或者像這樣以程式化的方式建立計時器控制項:

System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
myTimer.Interval = 1000; // 1 second interval
myTimer.Tick += new EventHandler(TimerEventProcessor);
myTimer.Start();
System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
myTimer.Interval = 1000; // 1 second interval
myTimer.Tick += new EventHandler(TimerEventProcessor);
myTimer.Start();
$vbLabelText   $csharpLabel

在這裡,TimerEventProcessor 是一個事件處理器,每次發生 Tick 事件時都會被呼叫,這與 System.Timers.Timer 中的 Elapsed 事件類似。

進階計時器管理

使用計時器的線程安全

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

高精度定時

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

實用範例

範例:實作倒數計時器

定時器有用的常見情境是建立倒數計時器。 可以將計時器的間隔設定為一秒 (1000 毫秒),並在計時器每過一次就減少一個計數器。 當計數器到達零時,計時器停止,表示倒數結束。

using System;

namespace CountdownApp
{
    class Program
    {
        static int countdownTime = 10; // Countdown from 10 seconds

        public static void Main(string[] args) // Main method
        {
            StartCountdown();
            Console.ReadLine(); // Prevent console from closing immediately
        }

        static void StartCountdown()
        {
            var timer = new System.Timers.Timer(1000); // Tick every second
            timer.Elapsed += UpdateCountdown;
            timer.Enabled = true;
        }

        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(string[] args) // Main method
        {
            StartCountdown();
            Console.ReadLine(); // Prevent console from closing immediately
        }

        static void StartCountdown()
        {
            var timer = new System.Timers.Timer(1000); // Tick every second
            timer.Elapsed += UpdateCountdown;
            timer.Enabled = true;
        }

        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
            }
        }
    }
}
$vbLabelText   $csharpLabel

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

!a href="/static-assets/pdf/blog/csharp-timer/csharp-timer-2.webp">C# Timer (How It Works For Developers):圖 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);
}
$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");
    }
}
$vbLabelText   $csharpLabel

安裝 IronPDF。

您可以使用 NuGet Package Manager 執行此指令來安裝 IronPDF:

Install-Package IronPdf

範例

假設您需要產生 PDF 格式的每日報告,其中包含每日更新的資料。 為了簡單起見,我們將產生一份基本的 HTML 報告,並每隔 24 小時使用 IronPDF 將其轉換為 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}");
    }
}
$vbLabelText   $csharpLabel

輸出

執行程式碼後,控制台會顯示以下輸出。 在這裡,我修改了程式碼,以便快速輸出,因此,我使用了 10 秒的計時器。

C# Timer (How It Works For Developers):圖 3 - 控制台輸出

以下是生成的 PDF:

C# Timer (How It Works For Developers):圖 4 - PDF 報告

結論

C# Timer (How It Works For Developers):圖 5 - 授權

總而言之,將 C# Timers 與 IronPDF 整合在一起呈現了一種強大的方法,可在 .NET 應用程式中自動生成和管理 PDF 文件。 透過所提供的範例,我們探討了如何設定 C# 計時器,以定期觸發 PDF 產生任務,不論是為了頻繁測試的目的,或是排程報告的產生。

使用 C# 計時器,我們可以精確地控制 PDF 相關任務的執行時間,讓定期更新、報表產生或任何需要在排程中發生的任務得以執行。 IronPdf 提供了一種直接而有效的方式來建立、處理和儲存基於動態內容、HTML 或甚至網頁的 PDF 文件,從而增強了這種能力。

IronPdf 提供免費試用與授權資訊,並可取得授權以獲得完整的使用權與支援。 這提供了一個符合成本效益的方式,在您的 .NET 應用程式中實作全面的 PDF 功能。

常見問題解答

C# 中有哪些主要的定時器類別?

C# 提供了多個計時器類,包括用於伺服器應用程式的System.Timers.Timer和用於 Windows 窗體應用程式的System.Windows.Forms.Timer ,每個類別都滿足不同的執行緒和執行要求。

如何在C#中將HTML轉換為PDF?

您可以使用 IronPDF 的RenderHtmlAsPdf方法在 C# 中將 HTML 轉換為 PDF,該方法支援 CSS 和 JavaScript 等進階功能,使其成為產生報告和發票的理想選擇。

如何在 C# 應用程式中設定和管理計時器?

要在 C# 應用程式中設定計時器,請建立計時器類別的實例,指定其間隔,並將事件處理程序附加到其ElapsedTick事件,從而允許您按固定間隔執行程式碼。

在 C# 應用程式中使用計時器有哪些好處?

C# 中的計時器有利於自動化任務,例如安排定期資料庫檢查、實現倒數計時器以及觸發 PDF 生成等自動化流程。

IronPDF 如何在 C# 中實現 PDF 生成自動化?

IronPDF 可以使用 C# 計時器按預定時間間隔觸發 PDF 建立過程,從而自動產生 PDF,例如產生每日報告或發票。

如何處理 System.Timers.Timer 的執行緒問題?

System.Timers.Timer會在執行緒池執行緒上執行回調,這可能會導致執行緒安全性問題。正確的管理方法是確保使用InvokeBeginInvoke等技術將 UI 更新序列化回 UI 執行緒。

如何在 C# 中透過定時器事件更新 UI 元件?

要在 C# 中透過定時器事件更新 UI 元件,必須將回呼封送回 UI 線程,通常在 Windows 窗體應用程式中使用InvokeBeginInvoke方法。

定時器如何增強 C# 應用程式的功能?

定時器可以透過允許按特定時間間隔安排任務來增強功能,透過自動化提高應用程式的效率和反應速度。

如何在 C# 專案中安裝和使用 IronPDF?

可以使用 NuGet 套件管理器,透過指令 ` Install-Package IronPdf將 IronPDF 安裝到 C# 專案中。安裝完成後,您可以使用它的方法將 HTML 轉換為 PDF 並自動產生 PDF 檔案。

C# 中定時器有哪些實際應用範例?

C# 中計時器的實際應用範例包括實現倒數計時器、安排定期資料庫更新以及使用 IronPDF 自動產生每日 PDF 報告。

Jacob Mellor,Team Iron 首席技術官
首席技術長

Jacob Mellor 是 Iron Software 的首席技術官,也是一位富有遠見的工程師,率先開發了 C# PDF 技術。作為 Iron Software 核心程式碼庫的最初開發者,他自公司成立之初便參與塑造了其產品架構,並與執行長 Cameron Rimington 一起將其發展成為一家擁有 50 多名員工、服務於 NASA、特斯拉和全球政府機構的公司。

Jacob 於 1998 年至 2001 年在曼徹斯特大學獲得土木工程一級榮譽學士學位。 1999 年,他在倫敦創辦了自己的第一家軟體公司;2005 年,他創建了自己的第一個 .NET 元件。此後,他專注於解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF 和 IronSuite .NET 庫在全球 NuGet 上的安裝量已超過 3000 萬次,其基礎程式碼持續為全球開發者工具提供支援。憑藉 25 年的商業經驗和 41 年的程式設計專長,Jacob 始終致力於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代技術領導者。