Skip to content

Timer Component

Introduction

Description

The timer component is an important functional component in the ET framework, providing a complete timing task management solution. The main functions include:

  • Delayed execution of tasks
  • Cyclic timing tasks
  • Timer cancellation and destruction

Core Features

  • Multiple Timer Types: Supports one-time timers, repeating timers, and asynchronous waiting timers
  • Async Support: Provides asynchronous waiting interfaces, supporting modern asynchronous programming patterns
  • Performance Optimization: Uses efficient data structures to optimize timer lookup and management

Timer Types

1. One-time Timer (OnceTimer)

Used for executing one-time delayed tasks:

csharp
// Create a timer that executes after 3 seconds
long timerId = timerComponent.NewOnceTimer(TimeInfo.Instance.ClientNow() + 3000, type, args);

2. Repeated Timer (RepeatedTimer)

Used for executing periodically repeating tasks:

csharp
// Create a timer that executes every 1 second
long timerId = timerComponent.NewRepeatedTimer(1000, type, args);

3. Asynchronous Wait Timer (OnceWaitTimer)

Used for asynchronously waiting for a specific time:

csharp
// Asynchronously wait for 2 seconds
await timerComponent.WaitAsync(2000);

// Wait until a specific time
await timerComponent.WaitTillAsync(tillTime);

4. Frame Timer

Used for tasks that execute every frame:

csharp
// Create a timer that executes every frame
long timerId = timerComponent.NewFrameTimer(type, args);

Usage Recommendations

  1. Short-time waiting scenarios:

    • Recommended to use WaitTillAsync
    • Suitable for short waiting periods that need logic continuity
    • For example: brief animation waits, simple delay effects
  2. Long-time waiting scenarios:

    • Recommended to use NewOnceTimer
    • Suitable for long waiting periods that need hot updates
    • For example: long-term game state checks, periodic data synchronization
  3. Cyclic task scenarios:

    • Recommended to use NewRepeatedTimer
    • Suitable for tasks that need to be executed periodically
    • For example: inventory refresh, buff updates, etc.

Timer Management

Cancel Timer

csharp
// Cancel via timer ID
timerComponent.Remove(ref timerId);

Safety Considerations

  1. Time Check
  • Minimum interval for repeating timers is 100ms
  • Time intervals less than 100ms will trigger error messages
  1. Cancellation Mechanism
  • Provides Remove method to safely remove timers

Basic Usage

The following will demonstrate a simple example of using the timer with the MoveComponent component

MoveComponent.cs
csharp
public class MoveComponent : Entity, IAwake, IDestroy
{
}
MoveComponentSystem.cs
csharp
using System;
using UnityEngine;

namespace MH
{
    [EntitySystem]
    public class MoveComponentAwakeSystem : AwakeSystem<MoveComponent>
    {
        protected override void Awake(MoveComponent self)
        {
        }
    }

    [EntitySystem]
    public class MoveComponentDestroySystem : DestroySystem<MoveComponent>
    {
        protected override void Destroy(MoveComponent self)
        {
        }
    }
    public static class MoveComponentSystem
    {
        
    }
}

Now let's define the requirements:

  1. Output position information once every 1 second
  2. Stop the first timer after 5 seconds

Next, go to the TimerInvokeType.cs file to add the timer types

csharp
namespace MH
{
    public static class TimerInvokeType
    {
        //test
        public const int TestTimer = 1;
        public const int CoroutineTimeout = 1001;



        //New TimeInvokeType
        public const int MoveComponent_TimeInvokeType1 = 1002;
        public const int MoveComponent_TimeInvokeType2 = 1003;
    }
}

After defining the timer types, modify MoveComponent.cs and MoveComponentSystem.cs

csharp
using System;
namespace MH
{
    public class MoveComponent : Entity, IAwake, IDestroy
    {
        public float X;
        public float Y;
        public float Z;

        public long TimerId1;
        public long TimerId2;
    }
}
csharp
using System;
using UnityEngine;

namespace MH
{
    [Invoke(TimerInvokeType.MoveComponent_TimeInvokeType1)]
    public class MoveComponent_Timer1 : ATimer<MoveComponent>
    {
        protected override void Run(MoveComponent self)
        {
            Debug.Log($"Current: X:{self.X} Y:{self.Y} Z:{self.Z}");
        }
    }
    [Invoke(TimerInvokeType.MoveComponent_TimeInvokeType2)]
    public class MoveComponent_Timer2 : ATimer<MoveComponent>
    {
        protected override void Run(MoveComponent self)
        {
            self.Root.GetComponent<TimerComponent>().Remove(ref self.TimerId1);
            Debug.Log("Stop timer 1");
        }
    }
    [EntitySystem]
    public class MoveComponentAwakeSystem : AwakeSystem<MoveComponent>
    {
        protected override void Awake(MoveComponent self)
        {
            self.TimerId1 = self.Root.GetComponent<TimerComponent>().NewRepeatedTimer(
                1000,
                TimerInvokeType.MoveComponent_TimeInvokeType1,
                self
            );
            self.TimerId2 = self.Root.GetComponent<TimerComponent>().NewOnceTimer(
                TimeInfo.Instance.ClientNow() + 5000,
                TimerInvokeType.MoveComponent_TimeInvokeType2,
                self
            );
        }
    }

    [EntitySystem]
    public class MoveComponentDestroySystem : DestroySystem<MoveComponent>
    {
        protected override void Destroy(MoveComponent self)
        {
            var timerComponent = self.Root.GetComponent<TimerComponent>();
            timerComponent.Remove(ref self.TimerId1);
            timerComponent.Remove(ref self.TimerId2);
        }
    }
    public static class MoveComponentSystem
    {
    }
}

Now, go to the MainInit_EventView script to add the MoveComponent component to Root

csharp
namespace MH
{
    [Event(SceneType.Main)]
    public class MainInit_EventView : AEvent<Scene, Main_Init>
    {
        protected override async ETTask Run(Scene scene, Main_Init a)
        {
            //...
            scene.AddComponent<MoveComponent>();
        }
    }
}

Effect Demonstration

Effect Video

The following video demonstrates the timer component effect

Technical Support

Get Help

  • 💬 Join QQ group for discussion (ET Framework Group) : 474643097
  • ⭐ Follow the project on GitHub for the latest updates

Released under the MIT License.