在生產環境中測試,無水印。
在任何需要的地方都能運行。
獲得 30 天的全功能產品。
在幾分鐘內上手運行。
試用產品期間完全訪問我們的支援工程團隊
在C#中,計時器類是用於在指定間隔調度執行代碼的強大工具。 無論您正在開發 Windows Form 應用程式還是控制台應用程式,了解如何使用計時器都可以大大提高應用程式的功能性。 本教程將引導您了解在 C# 中使用計時器的基本知識,包括如何設置計時器、處理其事件,以及確保它們在應用程式中順利運行。 我們還將討論如何使用IronPDF 進行 C# 應用程序中的自動化 PDF 生成,以在 C# 中使用計時器自動生成 PDF。
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
此簡單設置創建一個每兩秒滴答一次的計時器。 但是,要讓計時器執行動作,您需要將其連接到事件處理程序。
通過將經過事件處理程序附加到System.Timers.Timer的Elapsed事件,您可以確保應用程式能夠在每個間隔執行任務,從而有效地回應基於時間的觸發器。 每當計時器的間隔時間過去時,這個事件就會被觸發。 您可以將處理程序附加到此事件,以指定計時器滴答時應發生的情況:
timer.Elapsed += OnTimedEvent;
timer.Elapsed += OnTimedEvent;
timer.Elapsed += OnTimedEvent
在上述代碼中,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
此方法僅在計時器逾時時將當前時間列印到控制台,展示如何響應計時器事件。
在設定好計時器及其事件處理程序後,您需要啟動計時器。 您可以通過將其Enabled屬性設置為true或調用Start方法來完成:
timer.Enabled = true; // or timer.Start();
timer.Enabled = true; // or timer.Start();
timer.Enabled = True ' or timer.Start();
要停止計時器,您可以將Enabled設為false或呼叫Stop方法。 這對於防止您的應用程序在不需要時運行不必要的操作至關重要。
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()
在此,TimerEventProcessor 是一個事件處理程序,它會在每次發生 Tick 事件時被調用,這類似於 System.Timers.Timer 中的 Elapsed 事件。
在使用計時器時,了解應用程式的線程模型至關重要。 System.Timers.Timer 和 System.Threading.Timer 在執行緒池執行緒上執行其回調,允許平行執行。 然而,如果您的回調方法修改了共享數據或與用戶界面元素交互,這可能會導致線程安全問題。 若要從計時器的回調安全地更新 UI 元素,您必須使用特定於應用程式類型的技術將回調調度回 UI 執行緒(例如,在 Windows Forms 中使用 Invoke 或 BeginInvoke)。
對於需要高精度計時的應用程式(例如,多媒體應用程式或遊戲),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
以下是上述程式碼的輸出:
定時器可以用來定期檢查資料庫,例如查詢新資料或清理舊記錄。 此示例設置了一個計時器,每小時查詢一次資料庫:
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
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
您可以通過執行以下命令,使用 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
執行程式碼後,將在控制台顯示以下輸出。 在這裡,我修改了程式碼以加快輸出速度,所以我使用了10秒計時器。
以下是生成的 PDF:
總之,將 C# 計時器與 IronPDF 結合使用,為 .NET 應用程式中的 PDF 文件生成和管理提供了一種強大的自動化方法。 通過提供的範例,我們已探討如何設置 C# 計時器以定期觸發 PDF 生成任務,無論是為了頻繁的測試目的還是排程的報告生成。
使用 C# 計時器,我們可以精準控制 PDF 相關任務的執行時間,從而實現定期更新、報表生成或任何需按計畫進行的任務。 IronPDF 增強了這項功能,提供了一種簡單且高效的方法,基於動態內容、HTML,甚至是網頁來創建、操作和保存 PDF 文件。
IronPDF 提供免費試用版與授權資訊,可透過持有授權來獲得完整的訪問權限與支援。 這為您在 .NET 應用程式中實現綜合 PDF 功能提供了一種具有成本效益的方法。