You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Gatling每隔X分钟在后台执行任务?

Hey there! Let's walk through how to set up Gatling to run your X/Y/Z request scenario in the background every X minutes, while handling access token authentication smoothly.

Handling Access Token Authentication

First, you need a reliable way to manage the access token since it’ll likely expire before your recurring tasks finish. Here are two practical approaches:

Option 1: Fetch a Fresh Token Before Each Task

If your token’s lifespan is shorter than your X-minute interval, or you don’t mind a small overhead, just grab a new token at the start of every task run. This keeps things straightforward:

val fetchAccessToken = exec(http("Retrieve Access Token")
  .post("/auth/token")
  .formParam("grant_type", "client_credentials")
  .formParam("client_id", "${clientId}") // Load these from config/env vars
  .formParam("client_secret", "${clientSecret}")
  .check(jsonPath("$.access_token").saveAs("accessToken")))

Option 2: Background Token Refresh (For Longer-Lived Tokens)

If your token lasts longer than X minutes (e.g., 2 hours), run a dedicated background scenario to refresh it automatically before expiry. This avoids redundant token requests:

First, create a thread-safe token store to share the token across scenarios:

object TokenStore {
  @volatile private var currentToken: String = ""
  @volatile private var expiryTime: Long = 0

  def getValidToken: String = currentToken
  def needsRefresh: Boolean = System.currentTimeMillis() >= expiryTime

  def updateToken(newToken: String, expiresInSeconds: Int): Unit = {
    currentToken = newToken
    // Refresh 1 minute early to avoid race conditions
    expiryTime = System.currentTimeMillis() + (expiresInSeconds - 60) * 1000
  }
}

Then build the refresh scenario:

val tokenRefreshScenario = scenario("Auto-Refresh Access Token")
  .forever {
    exec(fetchAccessToken)
      .exec(session => {
        val token = session("accessToken").as[String]
        val expiresIn = session("expiresIn").as[Int]
        TokenStore.updateToken(token, expiresIn)
        session
      })
      .pause(session => {
        // Wait until 1 minute before expiry to refresh again
        TokenStore.expiryTime - System.currentTimeMillis()
      })
  }
Building Your Recurring Task Scenario

Next, define the scenario that runs your X/Y/Z requests. Adjust based on your token approach:

If Using Option 1 (Per-Task Token Fetch)

val recurringTaskScenario = scenario("Run X/Y/Z Requests")
  .exec(fetchAccessToken)
  .exec(http("Execute Request X")
    .get("/api/endpoint-x")
    .header("Authorization", "Bearer ${accessToken}"))
  .exec(http("Execute Request Y")
    .post("/api/endpoint-y")
    .header("Authorization", "Bearer ${accessToken}")
    .body(StringBody("""{"payload": "your-test-data"}""")).asJson)
  .exec(http("Execute Request Z")
    .put("/api/endpoint-z/${resource-id}")
    .header("Authorization", "Bearer ${accessToken}"))

If Using Option 2 (Global Token Store)

val recurringTaskScenario = scenario("Run X/Y/Z Requests")
  .exec(http("Execute Request X")
    .get("/api/endpoint-x")
    .header("Authorization", s"Bearer ${TokenStore.getValidToken}"))
  // Repeat the pattern for requests Y and Z with the same Authorization header
Scheduling the Background Task

Use Gatling’s injection scheduling to run your task every X minutes. Start with an immediate run, then repeat at your desired interval:

val taskIntervalMinutes = 5 // Replace with your actual X value

setUp(
  // Add this line only if you're using Option 2 for token refresh
  tokenRefreshScenario.inject(atOnceUsers(1)),
  recurringTaskScenario.inject(
    atOnceUsers(1), // Run once immediately
    schedule(0 seconds, taskIntervalMinutes minutes).inject(atOnceUsers(1)) // Repeat every X minutes
  )
).protocols(http.baseUrl("https://your-backend-domain.com"))
Running Gatling in the Background

To keep Gatling running seamlessly in the background (especially on servers), use a command like this (Linux/macOS):

nohup gatling.sh -s com.yourcompany.YourSimulationClass -rf ./results &

This runs Gatling in the background, logs output to nohup.out, and saves test results to the results directory.


内容的提问来源于stack exchange,提问作者Robin van den Berg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:11:28