Temporal 功能特性

Temporal 提供了全新的开发原语,旨在简化您的代码,让您能以更快的速度构建更多功能。在运行时,它具备容错性和极易扩展的特性,确保您的应用能够更可靠地实现大规模增长。

应用状态自动保存

告别状态机编写

Temporal 会捕获您函数的完整状态(变量、线程、阻塞调用),因此您无需维护复杂的状态机代码,即可获得状态机带来的所有好处。

async function transfer(
  fromAccount: string,
  toAccount: string,
  amount: number,
) {
  // These are activities, not regular functions.
  // Activities may run elsewhere, and their return value
  // is automatically persisted by Temporal.
  await myActivities.withdraw(fromAccount, amount);
  try {
    await myActivities.deposit(toAccount, amount);
  } catch {
    await myActivities.deposit(fromAccount, amount);
  }
}
        

原生重试机制

设置重试策略,无需编写重试代码

Temporal 允许您为 Activity 定义指数退避重试策略,因此您无需在应用代码中编写重试逻辑。重试持续时间可以根据需要任意长,甚至长达数月。

@activity.defn
async def compose_greeting(input: ComposeGreetingInput) -> str:
    print(f"Invoking activity, attempt number {activity.info().attempt}")
    # Fail the first 3 attempts, succeed the 4th
    if activity.info().attempt < 4:
        raise RuntimeError("Intentional failure" )
    return f"{input.greeting}, {input.name}!"


@workflow.defn
class GreetingWorkflow:
    @workflow.run
    async def run(self, name: str) -> str:
        # By default activities will retry, backing off an initial interval and
        # then using a coefficient of 2 to increase the backoff each time after
        # for an unlimited amount of time and an unlimited number of attempts.
        # We'll keep those defaults except we'll set the maximum interval to
        # just 2 seconds.
        return await workflow.execute_activity(
            compose_greeting,
            ComposeGreetingInput("Hello", name),
            start_to_close_timeout =timedelta(seconds=10),
            retry_policy=RetryPolicy(maximum_interval=timedelta(seconds=2)),
        )
        

超时/定时器

等待 3 秒或 3 个月

设置定时器来等待数天、数周甚至数月,即使在等待期间发生中断或服务器重启,也不会影响工作流的执行。

import { proxyActivities, sleep } from "@temporalio/workflow";
import type { Activities } from "./activities";
const { hasUpgraded, sendReminderEmail } = proxyActivities<Activities>({
  startToCloseTimeout: "10 seconds",
});

async function startTrial(user: string) {
  while (!(await hasUpgraded(user))) {
    await sendReminderEmail(user);
    await sleep("30 days");
  }
}
        

Schedules

使用调度,而非 Cron

Temporal 提供了一种调度工作流(类似于 cron 任务)的能力,并支持根据需要暂停、重启和停止这些工作流。

await new Client().schedule.create({
  action: {
    type: "startWorkflow",
    workflowType: reminderWorkflow,
    args: [
      "♻️ Dear future self, please take out the recycling tonight. Sincerely, past you ❤️",
    ],
    taskQueue: "schedules",
  },
  scheduleId: "sample-schedule",
  spec: {
    calendars: [
      {
        comment: "every wednesday at 8:30pm",
        dayOfWeek: "WEDNESDAY",
        hour: 20,
        minute: 30,
      },
    ],
  },
});
        

惯用的语言支持

以您擅长的语言,像冠军一样编码

Temporal 让您能够使用 Go、Java、TypeScript、Python 和 .NET 等 SDK(甚至支持部署多语言工作流)简单地进行持久化执行开发。

@dataclass
class GreetingParam:
    name: str


@workflow.defn
class GreetingWorkflow:
    @workflow.defn
    async def run(self, param: GreetingParam) -> str:
        return await workflow.execute_activity(
            greet,
            param,
            schedule_to_close_timeout=timedelta(seconds=30),
        )
        

人机交互 (Human in the Loop)

整合人工交互环节

使用包括人工操作在内的外部源,与工作流实现无缝交互。

func Accept(ctx workflow.Context, input *AcceptWorkflowInput) (*AcceptWorkflowResult, error) {
	err := emailCandidate(ctx, input)
	if err != nil {
		return nil, err
	}
	submission, err := waitForSubmission(ctx)
	if err != nil {
		return nil, err
	}
	return &AcceptWorkflowResult{Submission: submission},
		nil
}
        

执行可见性

无需猜测运行状态

Temporal 允许您逐步检查、重放和回溯每一次工作流执行过程。

Timeline

本地开发模型

本地开发,全球部署

使用您偏好的语言在本地编写代码,然后利用您现有的软件交付机制部署工作流和 Activity。

了解 Temporal Cloud

brew install temporal && temporal server start-dev

更多 设置本地环境 的方法。

graphic
Recent Workflows

无需纠结开发模式,直接交付代码。

事件驱动架构

事件驱动架构和基于队列的设计虽然承诺了易于部署和扩展,但对于开发来说简直是一场噩梦。

立即阅读:事件驱动架构 - 更好的前进之路 ›

无 Temporal 时
事件驱动应用在运行时松耦合,但在构建时高度耦合。这给错误处理和状态在不同服务间的传递带来了巨大复杂性。

使用 Temporal 后
应用状态、重试和错误处理被抽象化,您无需再为此编写代码。系统测试变得轻而易举,因为 Temporal 消除了常见的故障场景。

EDA Diagram

SAGA 与分布式事务

Saga 模式确保了分布式服务间安全且一致的状态,因此序列中某个操作的失败会导致之前的操作通过补偿事务进行回滚。

立即阅读:使用 Temporal 自动化 Saga 模式 ›

无 Temporal 时
Saga 通常需要大量的预先规划,因为没有中央系统来管理协调和可见性。调试意外的故障模式可能非常棘手。

使用 Temporal 后
工作流定义让您能够更轻松地理解、调试和修改 Saga。补偿操作间的耦合度降低,且您的应用代码保持整洁。

Saga Diagram

批处理

创建批处理进程是为了在大量甚至少量数据集上执行定义明确的函数。

无 Temporal 时
通常,批处理进程规模较大,当它们失败时,您几乎无法了解哪里失败了、哪些完成了、哪些还未完成。

使用 Temporal 后
批处理中的每个执行都成为一个已捕获状态的工作流执行,因此在失败时,您可以清楚地知道哪些已完成,并从何处重启进程。

Batch Processing Diagram

定时任务与 Cron

多年来,我们一直依赖 Cron 来调度在特定时间或定期执行的任务。

无 Temporal 时
Cron 很大程度上是一个手动过程,可能不可靠,且对执行过程几乎没有控制力。

使用 Temporal 后
您可以用“调度工作流”来替代 Cron,实现可靠执行。您可以启动、暂停它们,甚至可以通过信号指令在工作流中按需启动它们。

Schedules Diagram

状态机

状态机通常用于定义和管理应用程序内实体的有效状态和转换,根据您的应用不同,它们可能非常复杂。

立即阅读:简化状态机 ›

无 Temporal 时
随着每个新状态的增加,状态机代码的复杂性和长度会不断增长,对其进行维护和测试可能是一项挑战。

使用 Temporal 后
您的函数和工作流的完整状态会被捕获,因此您无需再进行自动化、跟踪和验证状态,从而可以消除或避免使用状态机。

State Machine Diagram
Globe with pixelated continents and orbitting dashed lines

Temporal Cloud

在 11 个以上区域提供可靠、可扩展、无服务器的 Temporal 服务

立即使用 Temporal 服务,无需烦琐配置,尽享安心。使用我们的托管服务,只需为您使用的资源付费;该服务由 Temporal 项目的创始团队开发、管理并提供支持。

Temporal Cloud

在 11 个以上区域提供可靠、可扩展、无服务器的 Temporal 服务

立即使用 Temporal 服务,无需烦琐配置,尽享安心。使用我们的托管服务,只需为您使用的资源付费;该服务由 Temporal 项目的创始团队开发、管理并提供支持。

Globe with pixelated continents and orbitting dashed lines

Temporal Cloud

在 11 个以上区域提供可靠、可扩展、无服务器的 Temporal 服务

立即使用 Temporal 服务,无需烦琐配置,尽享安心。使用我们的托管服务,只需为您使用的资源付费;该服务由 Temporal 项目的创始团队开发、管理并提供支持。

Globe with pixelated continents and orbitting dashed lines

构建坚不可摧的应用程序

为您的应用程序和服务提供持久执行。