In general this is not possible as you meant it, every time that some EVM instructions are executed there must be someone who is paying for the GAS. So it's not possible to write functions that are automatically triggered and executed when arbitrary situations occur.
However, for your particular situation:
- if you mean receiving Ether it would be possible simply writing a
- if the token that your contract is receiving implements a callback mechanism (as for the ERC1363) this would be possible implementing the
ERC1363Receiver interface in your contract.
- if you are deploying the token contract too you can virtually do whatever you want
I want to emphasize how in each of these three hypotheses someone has to pay for the GAS that for the first two cases it must be the one that transfers the token (not necessarily the owner).