Skip to content
Agentmart
Submit a tool

advpl-jobs-rpc

JOBs e RPC no Protheus — Main Function, RpcSetEnv(emp,fil,user,pwd,env,modulo), PREPARE/END ENVIRONMENT, StartJob, MsRunInThread.

Skill by replybr

IndexedMIT
Write a review

Chalk Labs

Need help deploying advpl-jobs-rpc?

Chalk Labs sets up agents like this inside real teams: connected to your tools, tested on your data, with a human in the loop where it matters.

Book a call

Install

Works with Claude Code, Claude apps, Codex, Cursor, Gemini CLI, GitHub Copilot, VS Code, OpenCode, Goose, Windsurf. Read the repository before you give any tool access to your data.

npx agentmarket install skill/replybr-advpl-jobs-rpc

Asks which of your tools to add it to (Claude Code, Codex, Cursor, VS Code, Windsurf, Gemini CLI, Claude Desktop) and shows the change first. See https://agentmart.dev/cli.

Get the weekly diff

The weekly diff: one email a week with new agent tools, notable updates and grade changes, plus security alerts for tools you follow. Double opt-in, one-click unsubscribe.

We use your email only for this newsletter. Privacy

About

JOBs e RPC no Protheus — Main Function, RpcSetEnv(emp,fil,user,pwd,env,modulo), PREPARE/END ENVIRONMENT, StartJob, MsRunInThread. Funções proibidas em JOB (MsgInfo, Aviso, Help, FwAlertHelp). Use ao trabalhar com processo agendado, scheduler ou job assíncrono.

No reviews yet. Installed it? Reviews come from verified installers only. How reviews work

Permissions

What this skill can do and what it asks for, from its SKILL.md. Checked Oct 25, 2026.

Tools
No tools found
Secrets
None asked for
Install scripts
None found

Network hosts it talks to 1

  • codeload.github.com · found in install command

Files it touches

  • ~/.claude/skills/advpl-jobs-rpc

What's inside

Skill name
advpl-jobs-rpc
Description
JOBs e RPC no Protheus — Main Function, RpcSetEnv(emp,fil,user,pwd,env,modulo), PREPARE/END ENVIRONMENT, StartJob, MsRunInThread. Funções proibidas em JOB (MsgInfo, Aviso, Help, FwAlertHelp). Use ao trabalhar com processo agendado, scheduler ou job assíncrono.
License
MIT
Instructions
203 lines in SKILL.md · view on GitHub

Agent Skills spec issues

  • name: missing

Files (1)

  • SKILL.md

SKILL.md (first lines)

# advpl-jobs-rpc — Execução headless no Protheus

Quando o Protheus precisa executar código **sem usuário humano logado** (cron-like jobs, scheduler, integrações batch, RPC chamado por sistema externo), o entrypoint não é `User Function` — é **`Main Function`** disparada via configuração do `appserver.ini` ou via `StartJob`/`CallProc`/`MsRunInThread`.

Diferenças fundamentais para fluxo de UI:

- **Não há `cFilAnt`/`cEmpAnt` preenchidos** — você abre o ambiente explicitamente com `RpcSetEnv`.
- **Não pode chamar UI** (`MsgInfo`, `Aviso`, `Help`, `FwAlertHelp`, `MsgBox`) — trava o JOB para sempre.
- **Erros precisam ser logados em arquivo/ConOut**, não em diálogo modal.

## Quando usar

- Edit/criação de fonte com `Main Function`.
- Usuário menciona "JOB", "scheduler", "agendamento", "rotina batch", "integração em background", "thread", "RPC".
- Aparece `RpcSetEnv`, `PrepareIn`, `StartJob`, `CallProc`, `MsRunInThread`, `Sleep` em fonte legacy.
- Investigação de "rotina rodou mas não fez nada" (provavelmente travada em `MsgInfo`).

## Estrutura mínima de JOB

```advpl
#include "TOTVS.CH"

/*/{Protheus.doc} XYZJob
JOB de integracao de pedidos diaria.
Disparado por scheduler do appserver.ini.
/*/
Main Function XYZJob(cEmp, cFil)
    Local cEmpDef := If(Empty(cEmp), "01",   AllTrim(cEmp))
    Local cFilDef := If(Empty(cFil), "0101", AllTrim(cFil))

    // Abre ambiente Protheus
    RpcSetType(3)              // 3 = job sem licenca de UI
    RpcSetEnv(cEmpDef, cFilDef, "admin", "totvs", "FAT", "XYZJob",,, .F.)

    ConOut("[" + Time() + "] XYZJob iniciado em " + cEmpDef + "/" + cFilDef)

    Begin Sequence
        // Lógica do job
        ProcessaPedidos()
    Recover Using oErr
        ConOut("[" + Time() + "] XYZJob ERRO: " + oErr:Description)
        ConOut(oErr:ErrorStack)
    End Sequence

    ConOut("[" + Time() + "] XYZJob finalizado")
    RpcClearEnv()
Return Nil

Static Function ProcessaPedidos()
    // ...
Return Nil
```

## `RpcSetEnv` — assinatura completa

```advpl
RpcSetEnv(cEmpresa, cFilial, cUser, cPassword, cAmbiente, cModulo, ;
         aTables, lShowFin, lAbreExclusivo)
```

| Posição | Parâmetro      | Tipo | Default        | O que faz                                  |
|---------|----------------|------|----------------|--------------------------------------------|
| 1       | `cEmpresa`     | C    | obrig          | Código da empresa (2 caracteres)           |
| 2       | `cFilial`      | C    | obrig          | Filial (4 caracteres)                      |
| 3       | `cUser`        | C    | `""`           | Usuário Protheus                           |
| 4       | `cPassword`    | C    | `""`           | Senha (criptografada com `EncryptPwd`)     |
| 5       | `cAmbiente`    | C    | env do appsv   | Ambiente (`PRODUCAO`, etc.)                |
| 6       | `cModulo`      | C    | `""`           | Sigla do módulo (`FAT`, `EST`, `FIN`)      |
| 7       | `aTables`      | A    | `{}`           | Tabelas a abrir (vazio = abre conforme módulo) |
| 8       | `lShowFin`     | L    | `.F.`          | Mostra dialog financeiro                   |
| 9       | `lAbreExclusivo` | L  | `.F.`          | Abre tabelas em modo exclusivo             |

**Sempre chame `RpcClearEnv()` no fim** para liberar conexão.

## `RpcSetType` — tipo de conexão

| Valor | Significado                                                   |
|-------|---------------------------------------------------------------|
| 1     | Default — consome licença "advpl/protheus" (UI-like)          |
| 2     | RPC web service                                               |
| 3     | JOB — **não consome licença de UI** (recomendado p/ batch)    |

**Em JOB sempre use `RpcSetType(3)` antes do `RpcSetEnv`.**

## `PREPARE ENVIRONMENT` / `END ENVIRONMENT` (alternativa)

Sintaxe declarativa equivalente:

```advpl
PREPARE ENVIRONMENT EMPRESA cEmp FILIAL cFil MODULO "FAT" TABLES "SA1","SC5","SF2"
    // código com ambiente aberto
END ENVIRONMENT
```

Cleanup automático no `END ENVIRONMENT`. Útil para escopo curto. Para JOBs longos, prefira `RpcSetEnv`/`RpcClearEnv` por controle explícito.

## Disparando jobs

### Via appserver.ini (scheduler do Protheus)

```ini
[ONSTART]
JOBS=XYZJob_Diario,ABCJob_NF

[XYZJob_Diario]
MAIN=XYZJob
ENVIRONMENT=PRODUCAO
NPARMS=2
PARM1=01
PARM2=0101
DAYS=1,2,3,4,5         ; segunda a sexta
HOUR=02:00             ; 2h da manhã
INSTANCES=1
ONSTART=
```

### Via `StartJob` em código

```advpl

From replybr/plugadvpl, MIT.

More from replybr/plugadvpl

Signals

Stars
0
Forks
5
Open issues
0
Last commit (this folder)
May 11, 2026 (5 months ago)

From GitHub (fetched Oct 24, 2026).

Details

License
MIT
First seen
Oct 24, 2026
Last checked
Oct 24, 2026

More from replybr

Done for you

Rather not set it up yourself?

Chalk Labs scopes, builds and runs agents for your team: the task audit, the eval harness, the integrations and the weekly ops report. Fixed scope, priced before we start.

See how we build AI agents →Read the case studies

Chalk Labs is a two-founder AI and growth studio. We build AI agents, CRMs and MVPs for Web3 and AI companies, and have shipped 50+ product and token launches.

launches shipped
50+
launches shipped
media placements
500+
media placements
founders on every account
2
founders on every account

Press we've placed: Forbes · CoinDesk · Decrypt · Cointelegraph · The Block

Rahil Jain, Co-founder, Chalk Labs. Ex-Goldman Sachs engineer. You talk to the person who builds it.

Get advpl-jobs-rpc running in your business

Tell us what you want to automate. A founder replies within one working day with a plan, not a pitch deck.

Goes to the Chalk Labs founders, not the newsletter. Privacy

Need help deploying advpl-jobs-rpc?

CallGet help
Cite this page

advpl-jobs-rpc skill. Agent Mart. https://agentmart.dev/skills/replybr-advpl-jobs-rpc (last updated 2026-10-24)