다음을 통해 공유


Timer 컨트롤 개요

업데이트: 2007년 11월

ASP.NET AJAX Timer 컨트롤은 정의된 간격으로 포스트백을 수행합니다. UpdatePanel 컨트롤과 Timer 컨트롤을 함께 사용하면 정의된 간격으로 부분 페이지 업데이트를 수행할 수 있습니다. Timer 컨트롤을 사용하여 전체 페이지를 게시할 수도 있습니다.

이 항목에는 다음과 같은 단원이 포함되어 있습니다.

  • 시나리오

  • 배경

  • 코드 예제

  • 클래스 참조

Timer 컨트롤 시나리오

다음과 같은 경우에 Timer 컨트롤을 사용합니다.

  • 전체 웹 페이지를 새로 고치지 않고 하나 이상의 UpdatePanel 컨트롤에 포함된 콘텐츠를 주기적으로 업데이트

  • Timer 컨트롤로 인해 포스트백이 발생할 때마다 서버에서 코드 실행

  • 전체 웹 페이지를 정의된 간격으로 웹 서버에 동기적으로 게시

배경

Timer 컨트롤은 JavaScript 구성 요소를 웹 페이지에 포함하는 서버 컨트롤입니다. JavaScript 구성 요소는 Interval 속성에 정의된 간격이 지나면 브라우저에서 포스트백을 시작합니다. Timer 컨트롤의 속성은 서버에서 실행되는 코드에 설정하며 이러한 속성은 JavaScript 구성 요소로 전달됩니다.

Timer 컨트롤을 사용할 경우 ScriptManager 클래스의 인스턴스를 웹 페이지에 포함해야 합니다.

Timer 컨트롤로 인해 포스트백이 발생한 경우 Timer 컨트롤은 서버에서 Tick 이벤트를 발생시킵니다. 페이지가 서버에 게시되는 경우 작업을 수행하기 위해 Tick 이벤트에 대한 이벤트 처리기를 만들 수 있습니다.

Interval 속성을 설정하여 포스트백 발생 간격을 지정하고 Enabled 속성을 설정하여 Timer를 설정 또는 해제합니다. Interval 속성은 밀리초 단위로 정의되며 기본값은 60,000밀리초 또는 60초입니다.

참고:

Timer 컨트롤의 Interval 속성을 작은 값으로 설정하면 웹 서버에 대한 트래픽이 상당히 증가할 수 있습니다. Timer 컨트롤을 사용하여 필요한 간격으로 콘텐츠를 새로 고치십시오.

다른 간격으로 다른 UpdatePanel 컨트롤을 업데이트해야 하는 경우 웹 페이지에 둘 이상의 Timer 컨트롤을 포함할 수 있습니다. 웹 페이지에 있는 둘 이상의 UpdatePanel 컨트롤에 대해 단일 Timer 컨트롤 인스턴스를 트리거할 수도 있습니다.

UpdatePanel 컨트롤 내부에서 Timer 컨트롤 사용

Timer 컨트롤이 UpdatePanel 컨트롤 내부에 포함되어 있는 경우 Timer 컨트롤은 자동으로 UpdatePanel 컨트롤에 대한 트리거로 작동합니다. UpdatePanel 컨트롤의 ChildrenAsTriggers 속성을 false로 설정하여 이러한 동작을 재정의할 수 있습니다.

UpdatePanel 컨트롤 내부에 포함된 Timer 컨트롤의 경우 각 포스트백이 끝날 때만 JavaScript 타이밍 구성 요소가 다시 만들어집니다. 따라서 페이지가 포스트백에서 반환될 때까지 시간 간격이 시작되지 않습니다. 예를 들어 Interval 속성이 60,000밀리초(60초)로 설정되어 있지만 포스트백에 3초가 걸리는 경우 다음 포스트백은 이전 포스트백 후 63초가 지나면 발생합니다.

다음 예제에서는 Timer 컨트롤을 UpdatePanel 컨트롤 내부에 포함하는 방법을 보여 줍니다.

<asp:ScriptManager  id="ScriptManager1" />
<asp:UpdatePanel  id="UpdatePanel1" 
    UpdateMode="Conditional">
  <contenttemplate>
    <asp:Timer id="Timer1" 
      Interval="120000" 
      OnTick="Timer1_Tick">
    </asp:Timer>
  </contenttemplate>
</asp:UpdatePanel>

UpdatePanel 컨트롤 외부에서 Timer 컨트롤 사용

Timer 컨트롤이 UpdatePanel 컨트롤 외부에 있는 경우 업데이트할 UpdatePanel 컨트롤에 대한 트리거로 Timer 컨트롤을 명시적으로 정의해야 합니다.

Timer 컨트롤이 UpdatePanel 컨트롤 외부에 있는 경우 포스트백이 처리될 때 JavaScript 타이밍 구성 요소가 계속 실행됩니다. 예를 들어 Interval 속성이 60,000밀리초(60초)로 설정되어 있으며 포스트백에 3초가 걸리는 경우 다음 포스트백은 이전 포스트백 후 60초가 지나면 발생합니다. 사용자는 57초만 지나면 UpdatePanel 컨트롤의 새로 고쳐진 콘텐츠를 볼 수 있습니다.

한 비동기 포스트백이 다음 포스트백 시작 전에 완료될 수 있도록 Interval 속성의 값을 설정해야 합니다. 이전 포스트백이 처리될 때 새 포스트백을 시작하면 첫 번째 포스트백이 취소됩니다.

다음 예제에서는 UpdatePanel 컨트롤 외부에서 Timer 컨트롤을 사용하는 방법을 보여 줍니다.

<asp:ScriptManager  id="ScriptManager1" />
<asp:Timer ID="Timer1"  Interval="120000" 
  OnTick="Timer1_Tick">
</asp:Timer>
<asp:UpdatePanel ID="UpdatePanel1" >
  <Triggers>
    <asp:AsyncPostBackTrigger ControlID="Timer1" 
        EventName="Tick" />
    </Triggers>
    <ContentTemplate>
      <asp:Label ID="Label1"  ></asp:Label>
  </ContentTemplate>
</asp:UpdatePanel>

코드 예제

다음 예제에서는 임의로 생성된 주가 및 해당 주가가 생성된 시간을 표시하는 UpdatePanel 컨트롤을 보여 줍니다. 기본적으로 Timer 컨트롤은 UpdatePanel의 콘텐츠를 10초마다 업데이트합니다. 사용자는 주가를 10초마다 업데이트하거나, 60초마다 업데이트하거나, 아예 업데이트하지 않도록 선택할 수 있습니다. 사용자가 주가를 업데이트하지 않도록 선택하면 Enabled 속성이 false로 설정됩니다.

<%@ Page Language="VB" AutoEventWireup="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" >
    <title>Timer Example Page</title>
    <script >
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            OriginalTime.Text = DateTime.Now.ToLongTimeString()
        End Sub

        Protected Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs)
            StockPrice.Text = GetStockPrice()
            TimeOfPrice.Text = DateTime.Now.ToLongTimeString()
        End Sub

        Private Function GetStockPrice() As String
            Dim randomStockPrice As Double = 50 + New Random().NextDouble()
            Return randomStockPrice.ToString("C")
        End Function

        Protected Sub RadioButton1_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
            Timer1.Interval = 10000
            Timer1.Enabled = True
        End Sub

        Protected Sub RadioButton2_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
            Timer1.Interval = 60000
            Timer1.Enabled = True
        End Sub

        Protected Sub RadioButton3_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
            Timer1.Enabled = False
        End Sub
</script>
</head>
<body>
    <form id="form1" >
    <asp:ScriptManager ID="ScriptManager1"  />
        <asp:Timer ID="Timer1" OnTick="Timer1_Tick"  Interval="10000" />

        <asp:UpdatePanel ID="StockPricePanel"  UpdateMode="Conditional">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="Timer1" />
        </Triggers>
        <ContentTemplate>
            Stock price is <asp:Label id="StockPrice" ></asp:Label><BR />
            as of <asp:Label id="TimeOfPrice" ></asp:Label>  
        </ContentTemplate>
        </asp:UpdatePanel>
        <div>
            <asp:RadioButton ID="RadioButton1" AutoPostBack="true" GroupName="TimerFrequency"  Text="10 seconds" OnCheckedChanged="RadioButton1_CheckedChanged" /><br />
            <asp:RadioButton ID="RadioButton2" AutoPostBack="true" GroupName="TimerFrequency"  Text="60 seconds" OnCheckedChanged="RadioButton2_CheckedChanged" /><br />
            <asp:RadioButton ID="RadioButton3" AutoPostBack="true" GroupName="TimerFrequency"  Text="Never" OnCheckedChanged="RadioButton3_CheckedChanged" /><br />
            <br />
        Page originally created at <asp:Label ID="OriginalTime" ></asp:Label>
        </div>
    </form>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" >
    <title>Timer Example Page</title>
    <script >
        protected void Page_Load(object sender, EventArgs e)
        {
            OriginalTime.Text = DateTime.Now.ToLongTimeString();
        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            StockPrice.Text = GetStockPrice();
            TimeOfPrice.Text = DateTime.Now.ToLongTimeString();
        }

        private string GetStockPrice()
        {
            double randomStockPrice = 50 + new Random().NextDouble();
            return randomStockPrice.ToString("C");
        }

        protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
        {
            Timer1.Enabled = true;
            Timer1.Interval = 10000;
        }

        protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
        {
            Timer1.Enabled = true;
            Timer1.Interval = 60000;
        }

        protected void RadioButton3_CheckedChanged(object sender, EventArgs e)
        {
            Timer1.Enabled = false;
        }

</script>
</head>
<body>
    <form id="form1" >
        <asp:ScriptManager ID="ScriptManager1"  />
        <asp:Timer ID="Timer1" OnTick="Timer1_Tick"  Interval="10000" />

        <asp:UpdatePanel ID="StockPricePanel"  UpdateMode="Conditional">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="Timer1" />
        </Triggers>
        <ContentTemplate>
            Stock price is <asp:Label id="StockPrice" ></asp:Label><BR />
            as of <asp:Label id="TimeOfPrice" ></asp:Label>  
            <br />

        </ContentTemplate>
        </asp:UpdatePanel>
        <div>
        <br />
        Update stock price every:<br />
        <asp:RadioButton ID="RadioButton1" AutoPostBack="true" GroupName="TimerFrequency"  Text="10 seconds" OnCheckedChanged="RadioButton1_CheckedChanged" /><br />
        <asp:RadioButton ID="RadioButton2" AutoPostBack="true" GroupName="TimerFrequency"  Text="60 seconds" OnCheckedChanged="RadioButton2_CheckedChanged" /><br />
        <asp:RadioButton ID="RadioButton3" AutoPostBack="true" GroupName="TimerFrequency"  Text="Never" OnCheckedChanged="RadioButton3_CheckedChanged" />
        <br />
        Page loaded at <asp:Label ID="OriginalTime" ></asp:Label>
        </div>
    </form>
</body>
</html>

자습서

연습: Timer 컨트롤 소개

연습: 여러 UpdatePanel 컨트롤에서 ASP.NET Timer 컨트롤 사용

클래스 참조

다음 표에서는 Timer 컨트롤의 핵심 서버 클래스를 보여 줍니다.

  • Timer
    정의된 간격으로 비동기적 또는 동기적 웹 페이지 포스트백을 수행합니다.

참고 항목

개념

부분 페이지 렌더링 개요

UpdatePanel 컨트롤 개요